Python:尝试缩小字符串并除去空格以外的非字母数字字符


问题内容

我正在尝试从字符串中删除除空格以外的所有非字母数字字符,但似乎无法弄清楚如何排除空格。我目前正在这种方式:

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()