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

时间:2014-12-14 20:50:02

标签: python string numbers extract

我在Python中有以下字符串。

"My number is 5"

如何查看字符串是否包含数字并随后将其解压缩,从而为我提供字符串“5”?

编辑:通过使用re模块,我现在得到结果[u,'5']。如何从这个结果中得到5号?

1 个答案:

答案 0 :(得分:2)

你需要使用正则表达式:

import re
my_num = re.findall("\d+","my number is 5")

\d+匹配1次或多次[0-9]

演示从0-20提取数字:

>>> a ="my string may 0-20, but how to remove number like 30,22 etc"
>>> my_num = re.findall('\d+',a)
>>> [int(x) for x in my_num if int(x)<=20]
[0, 20]