Python 如何删除列表中的多个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14215338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove multiple characters in a list?
提问by user1768615
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.
这有效,但我正在寻找更多 pythonic 方式。
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.
+而-并不总是处于领先地位; 他们可以在任何地方。
采纳答案by Ashwini Chaudhary
Use str.strip()or preferably str.lstrip():
使用str.strip()或最好str.lstrip():
In [1]: x = ['+5556', '-1539', '-99','+1500']
using list comprehension:
使用list comprehension:
In [3]: [y.strip('+-') for y in x]
Out[3]: ['5556', '1539', '99', '1500']
using map():
使用map():
In [2]: map(lambda x:x.strip('+-'),x)
Out[2]: ['5556', '1539', '99', '1500']
Edit:
编辑:
Use the str.translate()based solutionby @Duncan if you've +and -in between the numbers as well.
使用str.translate()基于解决方案的@Duncan如果你已经+和-在数字之间为好。
回答by Rakesh
x = [i.replace('-', "").replace('+', '') for i in x]
回答by Duncan
Use string.translate(), or for Python 3.x str.translate:
使用string.translate(), 或用于 Python 3.x str.translate:
Python 2.x:
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:
Python 2.x Unicode:
>>> u"+5+3-2".translate({ord(c): None for c in '+-'})
u'532'
Python 3.x version:
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']
回答by jfd
string.translate()will only work on byte-string objects not unicode. I would use re.sub:
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']
回答by G Locarso
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)
Output :
HhEEeLLlOOFROlMTHEOTHERSIDEooEEEEEE
helloo
输出 :
嘿嘿嘿嘿
你好

