Python:尝试降低字符串并删除空格以外的非字母数字字符

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

关于Python:尝试降低字符串并删除空格以外的非字母数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693804/

相关文章:

python - 将 dict 字符串转换为字典列表以插入到 mongodb

python - 中大型站点的项目根目录中通常有十几个 django 应用程序吗?不觉得臃肿吗?

python - python 列表中的选项卡\n

python - Python标准库真的是标准的吗?

python - Pandas 中按月份和任意属性求和和绘图

Python子进程 "object has no attribute ' fileno'”错误

python - 具有多个 where 条件的 Numpy [TypeError : invalid type promotion]

python进程退出或崩溃毫无线索

python - 如何找出 setup.py 中传递给安装程序的版本?

python - 如何在模式匹配之前使用正则表达式将字符串拆分为多行