使用
str.strip()或最好
str.lstrip():
In [1]: x = ['+5556', '-1539', '-99','+1500']
使用
list comprehension:
In [3]: [y.strip('+-') for y in x]Out[3]: ['5556', '1539', '99', '1500']使用
map():
In [2]: map(lambda x:x.strip('+-'),x)Out[2]: ['5556', '1539', '99', '1500']编辑:
如果您同时也在数字之间,请使用@Duncan提供的
str.translate()基础解决方案。
+``-
使用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']Python 2.x Unipre:>>> u"+5+3-2".translate({ord(c): None for c in '+-'})u'532'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']


