繁体   English   中英

如何从字符串中删除所有内容并仅保留数字(比*** re.sub('[^ 0-9]','',str)***更快的东西)?

[英]How to remove everything from a string and leave behind only digits ( something faster than *** re.sub('[^0-9]', '', str) ***)?

我运行此行以删除字符串中除数字外的所有内容。

str = "a111.113ç"
str = re.sub('[^0-9]', '', str)

但也许不得不

import re

可能会减慢速度。

是否有一个更快速的版本而不导入re?

更新

也许我应该找出“ re”里面是什么,然后通过将函数直接粘贴到我的脚本中来将其带到我的脚本中?

使用filterstr.isdigit

>>> filter(lambda x: x.isdigit(), "a111.113ç")
'111113'

顺便说一句,不要使用str作为变量名。 它将隐藏一个内置函数/类型str

一种简单的方法是使用filter

filter(lambda x: 47 < ord(x) < 58, str)

如果您想提高速度,那么re可能是最佳选择。 Python进行迭代的速度不是很快,因此最好依赖一些专门针对此任务进行了优化的库。

这应该比正则表达式更快:

>>> ''.join(filter(str.isdigit, '3,14%_56'))
'31456'

另一种可能性是使用str.translate()

>>> delchars = ''.join(chr(i) for i in range(256) if not chr(i).isdigit())
>>> '3,14%_56'.translate(None, delchars)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM