使用正则表达式会起作用:
import re
integers = re.compile(r'(?<!\S)\d+(?!\S)')
integers.findall(stringy)
演示:
>>> import re
>>> stringy = "If y0u can 66.6 r34d 25 this, you're 29 t00 close."
>>> integers = re.compile(r'(?<!\S)\d+(?!\S)')
>>> integers.findall(stringy)
['25', '29']
对于较短的输入示例,.split()
and.isdigit()
列表理解仍然更快:
>>> import timeit
>>> timeit.timeit('[item for item in stringy.split() if item.isdigit()]', 'from __main__ import stringy')
3.1379640102386475
>>> timeit.timeit('integers.findall(stringy)', 'from __main__ import stringy, integers')
4.119225978851318
输入越长,它的改进就越小:
>>> stringy = ''.join([stringy for _ in range(100)])
>>> timeit.timeit('[item for item in stringy.split() if item.isdigit()]', 'from __main__ import stringy', number=10000)
2.5325310230255127
>>> timeit.timeit('integers.findall(stringy)', 'from __main__ import stringy, integers', number=10000)
4.044284105300903