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

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

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

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

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


当前回答

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

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]

其他回答

另一种使用regex的方法:

''.join(re.split(r'[.;!?,]', s))

您可以使用翻译方法。

s.translate(None, '!.;,')

删除* % @ !从下面的字符串:

s = "this is my string,  and i will * remove * these ** %% "
new_string = s.translate(s.maketrans('','','*%,&@!'))
print(new_string)

# output: this is my string  and i will  remove  these  

你可以用这样的东西

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

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

最近我在钻研scheme,现在我觉得我擅长递归和求值。哈哈哈。分享一些新的方法:

首先,求值

print eval('string%s' % (''.join(['.replace("%s","")'%i for i in replace_list])))

第二,递归

def repn(string,replace_list):
    if replace_list==[]:
        return string
    else:
        return repn(string.replace(replace_list.pop(),""),replace_list)

print repn(string,replace_list)

嘿,别投反对票。我只是想分享一些新的想法。