我想提取字符串中包含的所有数字。哪个更适合这个目的,正则表达式还是 isdigit()
方法?
例子:
line = "hello 12 hi 89"
结果:
[12, 89]
最佳答案
我会使用正则表达式:
>>> import re
>>> re.findall(r'\d+', "hello 42 I'm a 32 string 30")
['42', '32', '30']
这也将匹配 bla42bla
中的 42。如果您只想要由单词边界(空格、句点、逗号)分隔的数字,您可以使用\b :
>>> re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")
['42', '32', '30']
以数字列表而不是字符串列表结束:
>>> [int(s) for s in re.findall(r'\b\d+\b', "he33llo 42 I'm a 32 string 30")]
[42, 32, 30]
关于python - 如何从 Python 中的字符串中提取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4289331/