Python:删除字符串列表中的多个字符

use*_*615 7 python string list

有这样的清单:

x = ['+5556', '-1539', '-99','+1500']
Run Code Online (Sandbox Code Playgroud)

如何以漂亮的方式删除+和 - ?

这有效,但我正在寻找更多的pythonic方式.

x = ['+5556', '-1539', '-99', '+1500']
n = 0
for i in x:
    x[n] = i.replace('-','')
    n += 1
n = 0
for i in x:
    x[n] = i.replace('+','')
    n += 1
print x
Run Code Online (Sandbox Code Playgroud)

编辑

+-并不总是处于领先地位; 他们可以在任何地方.

Dun*_*can 19

使用string.translate(),或者用于Python 3.x str.translate:

Python 2.x:

>>> import string
>>> identity = string.maketrans("", "")
>>> "+5+3-2".translate(identity, "+-")
'532'
>>> x = ['+5556', '-1539', '-99', '+1500']
>>> x = [s.translate(identity, "+-") for s in x]
>>> x
['5556', '1539', '99', '1500']
Run Code Online (Sandbox Code Playgroud)

Python 2.x unicode:

>>> u"+5+3-2".translate({ord(c): None for c in '+-'})
u'532'
Run Code Online (Sandbox Code Playgroud)

Python 3.x版本:

>>> no_plus_minus = str.maketrans("", "", "+-")
>>> "+5-3-2".translate(no_plus_minus)
'532'
>>> x = ['+5556', '-1539', '-99', '+1500']
>>> x = [s.translate(no_plus_minus) for s in x]
>>> x
['5556', '1539', '99', '1500']
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 15

使用str.strip()或优选str.lstrip():

In [1]: x = ['+5556', '-1539', '-99','+1500']
Run Code Online (Sandbox Code Playgroud)

使用list comprehension:

In [3]: [y.strip('+-') for y in x]
Out[3]: ['5556', '1539', '99', '1500']
Run Code Online (Sandbox Code Playgroud)

使用map():

In [2]: map(lambda x:x.strip('+-'),x)
Out[2]: ['5556', '1539', '99', '1500']
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您和@Duncan 之间使用str.translate()基础解决方案,也可以使用这些解决方案.+-


Rak*_*esh 11

x = [i.replace('-', "").replace('+', '') for i in x]
Run Code Online (Sandbox Code Playgroud)