如何从字符串中删除所有标点符号?

use*_*293 1 python regex string punctuation

从字符串中删除所有标点符号,x.我想使用re.findall(),但我一直在努力知道该怎么写吧..我知道我能得到所有通过书面标点符号:

import string
y = string.punctuation
Run Code Online (Sandbox Code Playgroud)

但如果我写:

re.findall(y,x) 
Run Code Online (Sandbox Code Playgroud)

它说:

 raise error("multiple repeat")
 sre_constants.error: multiple repeat
Run Code Online (Sandbox Code Playgroud)

有人可以解释我们应该在re.findall函数中写出什么?

the*_*eye 7

您可能甚至不需要RegEx.你可以简单地使用translate,就像这样

import string
print data.translate(None, string.punctuation)
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 5

中的几个字符在string.punctuation正则表达式中具有特殊含义。他们应该逃脱。

>>> import re
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> import re
>>> re.escape(string.punctuation)
'\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~'
Run Code Online (Sandbox Code Playgroud)

如果要匹配其中任何一个,请使用字符类([...]

>>> '[{}]'.format(re.escape(string.punctuation))
'[\\!\\"\\#\\$\\%\\&\\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~]'
Run Code Online (Sandbox Code Playgroud)
>>> import re
>>> pattern = '[{}]'.format(re.escape(string.punctuation))
>>> re.sub(pattern, '', 'Hell,o World.')
'Hello World'
Run Code Online (Sandbox Code Playgroud)