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

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

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

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

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


当前回答

另一种使用regex的方法:

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

其他回答

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'

另一种使用regex的方法:

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

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

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  

另外一个有趣的话题是将UTF-8重音字符从字符串中移除,将其转换为标准的非重音字符:

在python unicode字符串中删除重音的最佳方法是什么?

从主题摘录的代码:

import unicodedata

def remove_accents(input_str):
    nkfd_form = unicodedata.normalize('NFKD', input_str)
    return u"".join([c for c in nkfd_form if not unicodedata.combining(c)])
''.join(c for c in myString if not c in badTokens)