我有很多类似的字符串Current Level: 13.4 db.
我想只提取浮点数。我说的是浮动而不是十进制,因为它有时是整数。 RegEx 可以做到这一点还是有更好的方法?
如果您的浮点数始终以十进制表示法表示,例如
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4db.")
['13.4']
可能就足够了。
更强大的版本是:
>>> re.findall(r"[-+]?(?:\d*\.*\d+)", "Current Level: -13.2db 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)