我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
在Python 3.8中,这适用于我:
s.translate(s.maketrans(dict.fromkeys(',!.;', '')))
其他回答
我认为这是足够简单和将做!
list = [",",",","!",";",":"] #the list goes on.....
theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
if theString[i] in list:
newString += "" #concatenate an empty string.
else:
newString += theString[i]
这是一种方法。但是如果你厌倦了保留一个你想要删除的字符列表,你实际上可以通过使用你迭代的字符串的顺序号来做到这一点。订单号是该字符的ASCII值。0作为字符的ASCII码是48,小写z的ASCII码是122,所以:
theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
newString += ""
else:
newString += theString[i]
''.join(c for c in myString if not c in badTokens)
另一种使用regex的方法:
''.join(re.split(r'[.;!?,]', s))
您可以使用翻译方法。
s.translate(None, '!.;,')
也许有一种更现代、更实用的方式来实现你的愿望:
>>> subj = 'A.B!C?'
>>> list = set([',', '!', '.', ';', '?'])
>>> filter(lambda x: x not in list, subj)
'ABC'
请注意,对于这个特定的目的,它是相当夸张的,但一旦您需要更复杂的条件,过滤器就会派上用场