How can I remove multiple characters in a list?

后端 未结 5 897
天命终不由人
天命终不由人 2020-12-11 04:56

Having such list:

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

How can I remove + and - in nice way?

This works but I\'m looking f

5条回答
  •  悲哀的现实
    2020-12-11 05:23

    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.

提交回复
热议问题