Answer a question

Having such list:

x = ['+5556', '-1539', '-99','+1500']

How can I remove + and - in nice way?

This works but I'm looking for more pythonic way.

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

Edit

+ and - are not always in leading position; they can be anywhere.

Answers

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.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐