从Python中的字符串中提取数字

时间:2012-04-09 17:30:58

标签: python regex string

假设我有一个这种形式的字符串

this is a sentence 234225, and some 857307 other stuff, Time=72625, other stuff   

在Python中推断数字72625的最快方法是什么?

5 个答案:

答案 0 :(得分:10)

使用re.findall可以获得最简单的输出,适用于任意数量的匹配。

sent = "this is a sentence 234225, and some 857307 other stuff, Time=72625, other stuff"

import re

print re.findall("Time=(\d+)", sent)
# ['72625']

答案 1 :(得分:3)

如果

>>> st="this is a sentence 234225, and some 857307 other stuff, Time=72625, other stuff"

没有正则表达式的另一种方法是

>>> st.split("Time=")[-1].split()[0]
'72625'
>>> 

答案 2 :(得分:2)

import re
input = "this is a sentence 234225, and some 857307 other stuff, Time=72625, other stuff"
print re.search('Time=(\d+)', input).group(1)

答案 3 :(得分:0)

>>> import re
>>> x = 'this is a sentence 234225, and some 857307 other stuff, Time=72625, other stuff'
>>> re.search('(?<=Time=)\d+',x).group()
'72625'

答案 4 :(得分:-1)