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

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

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

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

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


当前回答

下面是more_itertools的方法:

import more_itertools as mit


s = "A.B!C?D_E@F#"
blacklist = ".!?_@#"

"".join(mit.flatten(mit.split_at(s, pred=lambda x: x in set(blacklist))))
# 'ABCDEF'

在这里,我们将在黑名单中找到的项目进行拆分,将结果平直并连接字符串。

其他回答

下面是more_itertools的方法:

import more_itertools as mit


s = "A.B!C?D_E@F#"
blacklist = ".!?_@#"

"".join(mit.flatten(mit.split_at(s, pred=lambda x: x in set(blacklist))))
# 'ABCDEF'

在这里,我们将在黑名单中找到的项目进行拆分,将结果平直并连接字符串。

另一种使用regex的方法:

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

这个怎么样,一行字。

reduce(lambda x,y : x.replace(y,"") ,[',', '!', '.', ';'],";Test , ,  !Stri!ng ..")

您可以使用翻译方法。

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

在Python 3.8中,这适用于我:

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