python - 如何从 Python 中的字符串中提取数字?

标签 python regex string numbers

我想提取字符串中包含的所有数字。哪个更适合这个目的,正则表达式还是 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/

相关文章:

python - 从前一行中减去具有 DataFrame 中前一组值的行

正则表达式从右侧提取不贪婪

regex - Perl 正则表达式 : count leading substrings

c++ - 如何轻松解析来自 GSM 模块的 AT 命令响应?

javascript - 如果是 "Strings are objects,"那么为什么我不能在它们上面存储属性?

python - 使用 "pointer"更新 tkinter 小部件参数

python - 用于查找 1000 位数字的 13 个连续数字的最大乘积的代码未给出所需的输出

javascript - 替换 Javascript 中正则表达式匹配的结果

c++ - 为什么 getline 的字符串版本是非成员函数?

python - 大量的 math.sqrt() 和 math.pow() 中的不准确性来自哪里?