如何用Python去除字符串中的符号?
我刚开始学习Python和正则表达式(RegEx),想知道怎么把字符串中的符号替换成空格。任何帮助都很棒。
比如说:
how much for the maple syrup? $20.99? That's ricidulous!!!
变成:
how much for the maple syrup 20 99 That s ridiculous
3 个回答
12
我经常直接打开控制台,查看对象的方法,很多时候解决方案就在里面:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
简单来说:用 string.replace()
。
36
有时候,弄清楚正则表达式的写法比直接在Python里写出来还要花时间:
import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
s = s.replace(char, ' ')
如果你需要其他字符,可以把它改成使用白名单,或者扩展你的黑名单。
白名单示例:
whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
if char in whitelist:
new_s += char
else:
new_s += ' '
使用生成器表达式的白名单示例:
whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
207
一种方法是使用正则表达式:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup 20 99 That s ridiculous '
\w
可以匹配字母、数字和下划线[^\w]
可以匹配任何不是字母、数字或下划线的东西