我试图从字符串中删除除空格之外的所有非字母数字字符,但似乎无法弄清楚如何排除空格。我目前正在这样做:
re.sub('[\W_]+', '', text).lower().strip()
但是运行我的函数会产生以下结果:
print removePunctuation('Hi, you!')
print removePunctuation(' No under_score!')
hiyou
nounderscore
我想要的位置:
hi you
no underscore
那么如何排除空间被替换呢?
我目前的最佳选择是:
re.sub('[^\s\w]+', '', text).lower().strip().replace('_','')
最佳答案
你可以用这个,
re.sub(r'[^\sa-zA-Z0-9]', '', text).lower().strip()
示例:
>>> import re
>>> def removePunctuation(s):
return re.sub(r'[^\sa-zA-Z0-9]', '', s).lower().strip()
>>> print removePunctuation('Hi, you!')
hi you
>>> print removePunctuation(' No under_score!')
no underscore
或
re.sub('(?!\s)[\W_]', '', text).lower().strip()
关于Python:尝试降低字符串并删除空格以外的非字母数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693804/