删除 Python 中的数字(正则表达式) [英] Delete digits in Python (Regex)

查看:31
本文介绍了删除 Python 中的数字(正则表达式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串中删除所有数字.但是,下一个代码也会删除任何单词中包含的数字.显然,我不想那样.我尝试了很多正则表达式都没有成功.

谢谢!

<小时>

s = "这个一定不能删,但是最后的数字是134411"s = re.sub("\d+", "", s)印刷

结果:

<块引用>

这个一定不是b删了,而是末尾的数字是

解决方案

在 \d+ 之前添加一个空格.

<预><代码>>>>s = "这个一定不是b3 delet3d,而是末尾的数字是134411">>>s = re.sub(" \d+", " ", s)>>>秒'这一定不是b3 delet3d,而是最后的数字是'

看了评论后,我决定形成一个更完整的答案.我认为这可以解释所有情况.

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)

I am trying to delete all digits from a string. However, the next code deletes as well digits contained in any word. Obviously, I don't want that. I have been trying many regular expressions with no success.

Thanks!


s = "This must not be deleted, but the number at the end yes 134411"
s = re.sub("\d+", "", s)
print s

Result:

This must not b deleted, but the number at the end yes

解决方案

Add a space before the \d+.

>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
>>> s = re.sub(" \d+", " ", s)
>>> s
'This must not b3 delet3d, but the number at the end yes '

Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)

这篇关于删除 Python 中的数字(正则表达式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆