如何从字符串中提取浮点数我有许多类似于Current Level: 13.4 db.我只想提取浮点数。我说的是浮点,而不是小数,因为它有时是完整的。RegEx能做到这一点吗?还是有更好的方法?
3 回答
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
>>> import re>>> re.findall("\d+\.\d+", "Current Level: 13.4 db.")['13.4']
>>> re.findall(r"[-+]?\d*\.\d+|\d+", "Current Level: -13.2 db or 14.2 or 3")['-13.2', '14.2', '3']
user_input = "Current Level: 1e100 db"for token in user_input.split(): try: # if this succeeds, you have your (first) float print float(token), "is a float" except ValueError: print token, "is something else"# => Would print ...## Current is something else# Level: is something else# 1e+100 is a float# db is something else
ABOUTYOU
TA贡献1812条经验 获得超5个赞
>>> import re>>> numeric_const_pattern = r""" ... [-+]? # optional sign ... (?: ... (?: \d* \. \d+ ) # .1 .12 .123 etc 9.1 etc 98.1 etc ... | ... (?: \d+ \.? ) # 1. 12. 123. etc 1 12 123 etc ... ) ... # followed by optional exponent part if desired ... (?: [Ee] [+-]? \d+ ) ? ... """>>> rx = re.compile(numeric_const_pattern, re.VERBOSE)>>> rx.findall(".1 .12 9.1 98.1 1. 12. 1 12") ['.1', '.12', '9.1', '98.1', '1.', '12.', '1', '12']>>> rx.findall("-1 +1 2e9 +2E+09 -2e-9")['-1', '+1', '2e9', '+2E+09', '-2e-9'] >>> rx.findall("current level: -2.03e+99db")['-2.03e+99']>>>
numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?' rx = re.compile(numeric_const_pattern, re.VERBOSE)rx.findall("Some example: Jr. it. was .23 between 2.3 and 42.31 seconds")
GCT1015
TA贡献1827条经验 获得超4个赞
scanf() Token Regular Expression%e, %E, %f, %g [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?%i [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)
\.
[.,]
Regular ExpressionInternational float [-+]?(\d+([.,]\d*)?|[.,]\d+)([eE][-+]?\d+)?
添加回答
举报
0/150
提交
取消