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

2024-03-29 00:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这张表格的一串

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

用Python推断72625的最快方法是什么?


Tags: and方法timeissomethissentence表格
3条回答
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)

如果

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

另一种不用regex的方法是

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

使用^{}可以获得最简单的输出,并可用于任何数量的匹配项。

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

import re

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

相关问题 更多 >