我想在python中删除字符串中的字符:

string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...

但我有很多字符必须删除。我想了一个清单

list = [',', '!', '.', ';'...]

但是如何使用列表来替换字符串中的字符呢?


当前回答

''.join(c for c in myString if not c in badTokens)

其他回答

你可以用这样的东西

def replace_all(text, dic):
  for i, j in dic.iteritems():
    text = text.replace(i, j)
  return text

这不是我自己的代码,来自这里,这是一篇伟大的文章,并深入讨论了这样做

我认为这是足够简单和将做!

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]

为什么不是一个简单的循环?

for i in replace_list:
    string = string.replace(i, '')

另外,避免将列表命名为“list”。它覆盖内置函数列表。

在Python 3.8中,这适用于我:

s.translate(s.maketrans(dict.fromkeys(',!.;', '')))

为什么不利用这个简单的函数:

def remove_characters(str, chars_list):
    for char in chars_list:
        str = str.replace(char, '')
  
    return str

使用功能:

print(remove_characters('A.B!C?', ['.', '!', '?']))

输出:

ABC