我需要从多个字符串中提取一个数字(时间值),如何优雅地实现?所有数字都是正数,最多有两位小数。(例如:2.3 / 40.09 / 101.4 - 没有使用E表示法的数字)。我需要的代码应该像以下伪代码一样执行:
>>> "It took 2.3 seconds".strip(everything but ".1234567890")
2.3
不要使用strip函数,使用正则表达式选择数字:
而不是strip函数,使用正则表达式选择数字:
import re
numbers = re.compile(r'\d+(?:\.\d+)?')
numbers.findall("It took 2.3 seconds")
演示:
>>> import re
>>> numbers = re.compile(r'\d+(?:\.\d+)?')
>>> numbers.findall("It took 2.3 seconds")
['2.3']
这会返回所有匹配项的列表;这样您就可以在字符串中查找多个数字:
>>> numbers.findall("It took between 2.3 and 42.31 seconds")
['2.3', '42.31']
.0123456789
以外的所有东西,所以我保持简单。 - Martijn Pieters如果您只想从字符串中删除所有不在另一个字符串中的字符,我建议使用以下方法:
>>> to_filter = "It took 2.3 seconds"
>>> "".join(_ for _ in to_filter if _ in ".1234567890")
'2.3'
这是一种非常天真的提取数字的方法,然而。如果您想要更多不仅仅是像您所要求的简单字符过滤器,您应该使用Martijn Pieters的答案。
-2.3
?+4.5e-127
?0xcafebabe
? - georg