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

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

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

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

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


当前回答

您可以使用翻译方法。

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

其他回答

在Python 3.8中,这适用于我:

s.translate(s.maketrans(dict.fromkeys(',!.;', '')))
''.join(c for c in myString if not c in badTokens)

您可以使用翻译方法。

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

简单的方法,

import re
str = 'this is string !    >><< (foo---> bar) @-tuna-#   sandwich-%-is-$-* good'

// condense multiple empty spaces into 1
str = ' '.join(str.split()

// replace empty space with dash
str = str.replace(" ","-")

// take out any char that matches regex
str = re.sub('[!@#$%^&*()_+<>]', '', str)

输出:

这是细绳,foo,酒吧,金枪鱼三明治——是——好

我在想一个解决办法。首先,我将字符串输入作为一个列表。然后我将替换列表中的项。然后通过join命令,我将返回list作为字符串。代码可以是这样的:

def the_replacer(text):
    test = []    
    for m in range(len(text)):
        test.append(text[m])
        if test[m]==','\
        or test[m]=='!'\
        or test[m]=='.'\
        or test[m]=='\''\
        or test[m]==';':
    #....
            test[n]=''
    return ''.join(test)

这将删除字符串中的任何内容。你怎么看?