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

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

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

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

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


当前回答

在Python 3.8中,这适用于我:

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

其他回答

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

您可以使用翻译方法。

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

Python 3,单行列表综合实现。

from string import ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
def remove_chars(input_string, removable):
  return ''.join([_ for _ in input_string if _ not in removable])

print(remove_chars(input_string="Stack Overflow", removable=ascii_lowercase))
>>> 'S O'

如果您正在使用python3并寻找翻译解决方案-函数已更改,现在接受1个参数而不是2个参数。

该参数是一个表(可以是字典),其中每个键都是要查找的字符的Unicode序数(int),值是替换值(可以是要将键映射到的Unicode序数或字符串)。

下面是一个用法示例:

>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'

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

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

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