如何从字符串中删除所有非整数?(Python) [英] How to remove all non-integers from a string? (Python)
本文介绍了如何从字符串中删除所有非整数?(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 python 很陌生.我有个问题.例如,当我从文件中读取一行时,我有一个看起来像这样的字符串.
thestring = '000,5\r\n'
如何从此字符串中删除所有非整数,然后将此字符串本身转换为整数?谢谢!
解决方案
使用 str.translate
,这可能是最快的方法:
使用regex
:
使用 str.join
和 str.isdigit
:
使用int()
得到整数:
时间比较:
<预><代码>>>>strs = strs*10**4>>>%timeit strs.translate(无,忽略)1000 个循环,最好的 3 个:每个循环 441 us>>>%timeit re.sub(r'[^\d]+','',strs)10 个循环,最好的 3 个:每个循环 20.3 毫秒>>>%timeit re.sub(r'[^0-9]+','',strs)100 个循环,最好的 3 个:每个循环 17.1 毫秒>>>%timeit "".join([x for x in strs if x.isdigit()])10 个循环,最好的 3 个:每个循环 19.2 毫秒I'm pretty new to python. I have a question. Say for example when I read a line from a file I have a string that looks like this.
thestring = '000,5\r\n'
How do I remove all non-integers from this string and then convert this string into an integer itself? Thanks!
解决方案
Using str.translate
, this is probably the fastest way to do this:
>>> strs = '000,5\r\n'
>>> from string import ascii_letters, punctuation, whitespace
>>> ignore = ascii_letters + punctuation + whitespace
>>> strs.translate(None, ignore)
'0005'
Using regex
:
>>> import re
>>> re.sub(r'[^\d]+','',strs) #or re.sub(r'[^0-9]+','',strs)
'0005'
Using str.join
and str.isdigit
:
>>> "".join([x for x in strs if x.isdigit()])
'0005'
Use int()
to get the integer:
>>> int('0005')
5
Timing comparisons:
>>> strs = strs*10**4
>>> %timeit strs.translate(None, ignore)
1000 loops, best of 3: 441 us per loop
>>> %timeit re.sub(r'[^\d]+','',strs)
10 loops, best of 3: 20.3 ms per loop
>>> %timeit re.sub(r'[^0-9]+','',strs)
100 loops, best of 3: 17.1 ms per loop
>>> %timeit "".join([x for x in strs if x.isdigit()])
10 loops, best of 3: 19.2 ms per loop
这篇关于如何从字符串中删除所有非整数?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文