Python 如何删除列表中的多个字符?
有这样的名单:Python 如何删除列表中的多个字符?,python,string,list,Python,String,List,有这样的名单: x = ['+5556', '-1539', '-99','+1500'] 如何以良好的方式删除+和-呢 这是可行的,但我正在寻找更多的蟒蛇方式 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 编辑 +
x = ['+5556', '-1539', '-99','+1500']
如何以良好的方式删除+和-呢
这是可行的,但我正在寻找更多的蟒蛇方式
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
编辑
+
和-
并不总是处于领先地位;它们可以在任何地方。使用或最好使用:
x = [i.replace('-', "").replace('+', '') for i in x]
使用列表理解
:
In [3]: [y.strip('+-') for y in x]
Out[3]: ['5556', '1539', '99', '1500']
使用map()
:
编辑:
如果在数字之间有+
和-
,请使用@Duncan基于的str.translate()
。使用string.translate()
,或者对于Python 3.xstr.translate
:
Python2.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']
string.translate()
只对字节字符串对象有效,而不是unicode。我会使用re.sub
:
>>> import re
>>> x = ['+5556', '-1539', '-99','+1500', '45+34-12+']
>>> x = [re.sub('[+-]', '', item) for item in x]
>>> x
['5556', '1539', '99', '1500', '453412']
输出:
Hheellloofromtheothersideooeee
你好
非常好的主意,但如果有更多的字符要删除,则替换为longI将使用@Duncan提供的
翻译
解决方案,以防数字之间有+-。@mgilson我编辑我的答案时,他的解决方案没有公布,所以现在是+1。是的,我根据时间戳算出了。我只是想既然有了一个更新(更好的IMHO)的答案,你应该知道它。当value
是unicode对象时,你仍然可以在Python 2上使用value.translate()
,但你需要传递一个不同的翻译映射。我更新了我的答案以包含此案例。问题不是删除重复项
>>> 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']
>>> import re
>>> x = ['+5556', '-1539', '-99','+1500', '45+34-12+']
>>> x = [re.sub('[+-]', '', item) for item in x]
>>> x
['5556', '1539', '99', '1500', '453412']
basestr ="HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE"
def replacer (basestr, toBeRemove, newchar) :
for i in toBeRemove :
if i in basestr :
basestr = basestr.replace(i, newchar)
return basestr
newstring = replacer(basestr,['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'], "")
print(basestr)
print(newstring)