我试图删除除字符串空格以外的所有非字母数字字符,但似乎无法弄清楚我是如何排除空格的 . 我现在这样做:
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('_','')
5 回答
你可以用这个,
Example:
OR
你可能更喜欢列表理解:
您可以使用str.translate删除标点符号:
对于python3:
在一个功能:
输出:
如果要删除前导空格,请添加条带 .
输出:
发电机理解怎么样?它比使用RegExp更具可读性 .
或作为
lambda
您可以从其他方面解决问题:
它给了
a b
所以你要说:删除所有非字母数字字符而不是空格或下划线字符 .