首页 > 解决方案 > 是否有一个函数可以从字符串中删除任何符号(%、# 等)?

问题描述

我想有效地从我的字符串中删除所有符号。

x = hello!!
r = dict.fromkeys(map(ord, '\n ' + string.punctuation))
x.translate(r)

我希望这会删除所有符号,而不仅仅是句号(。)

标签: pythonpython-3.x

解决方案


如何使用re.sub删除所有string.punctuation' \n'

x = re.sub('|'.join(map(re.escape, string.punctuation + ' \n')), '', x)

如果您只想保留字母和数字字符,也可以使用以下正则表达式:

x = re.sub('[^a-zA-Z0-9]', '', x)

推荐阅读