如何删除列表中的多个字符? [英] How can I remove multiple characters in a list?

查看:71
本文介绍了如何删除列表中的多个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有这样的列表:

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

如何以一种不错的方式删除+和-?

How can I remove + and - in nice way?

这可行,但我正在寻找更多的Python方式.

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.

推荐答案

使用 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()解决方案数字也是如此.

Use the str.translate() based solution by @Duncan if you've + and - in between the numbers as well.

这篇关于如何删除列表中的多个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆