有这样的清单:
x = ['+5556', '-1539', '-99','+1500']
我怎样才能很好地删除+和-?
这有效,但我正在寻找更多的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
+而且-并不总是处于领先地位;他们可以在任何地方。
+
-
使用str.strip()或最好str.lstrip():
str.strip()
str.lstrip()
In [1]: x = ['+5556', '-1539', '-99','+1500']
使用list comprehension:
list comprehension
In [3]: [y.strip('+-') for y in x] Out[3]: ['5556', '1539', '99', '1500']
使用map():
map()
In [2]: map(lambda x:x.strip('+-'),x) Out[2]: ['5556', '1539', '99', '1500']
编辑:
如果您同时也在数字之间,请使用@Duncan提供的str.translate()基础解决方案。+``-
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 Unicode: >>> 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']