How can I remove multiple characters in a list?
x = [i.replace('-', "").replace('+', '') for i in x]
Use str.strip()
or preferably str.lstrip()
:
In [1]: x = ['+5556', '-1539', '-99','+1500']
using list comprehension
:
In [3]: [y.strip('+-') for y in x]
Out[3]: ['5556', '1539', '99', '1500']
using map()
:
In [2]: map(lambda x:x.strip('+-'),x)
Out[2]: ['5556', '1539', '99', '1500']
Edit:
Use the str.translate()
based solution by @Duncan if you've +
and -
in between the numbers as well.
Use string.translate()
, or for 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 version:
>>> 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']