如何从字符串中提取浮点数 [英] How to extract a floating number from a string

查看:41
本文介绍了如何从字符串中提取浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多类似于 Current Level: 13.4 db. 的字符串,我只想提取浮点数.我说浮动而不是十进制,因为它有时是完整的.RegEx 可以这样做还是有更好的方法?

解决方案

如果你的浮点数总是用十进制表示法表示

<预><代码>>>>进口重新>>>re.findall("d+.d+", "当前级别:13.4 db.")['13.4']

可能就足够了.

更强大的版本是:

<预><代码>>>>re.findall(r"[-+]?d*.d+|d+", "当前等级:-13.2 db or 14.2 or 3")['-13.2', '14.2', '3']

如果您想验证用户输入,您也可以通过直接步进来检查浮点数:

user_input = "当前等级:1e100 db"对于 user_input.split() 中的令牌:尝试:# 如果这成功,你有你的(第一个)浮动打印浮点数(令牌),是一个浮点数"除了值错误:打印令牌,是别的东西"# =>会打印...## 当前是别的东西# 级别:是别的东西# 1e+100 是一个浮点数# db 是别的东西

I have a number of strings similar to Current Level: 13.4 db. and I would like to extract just the floating point number. I say floating and not decimal as it's sometimes whole. Can RegEx do this or is there a better way?

解决方案

If your float is always expressed in decimal notation something like

>>> import re
>>> re.findall("d+.d+", "Current Level: 13.4 db.")
['13.4']

may suffice.

A more robust version would be:

>>> re.findall(r"[-+]?d*.d+|d+", "Current Level: -13.2 db or 14.2 or 3")
['-13.2', '14.2', '3']

If you want to validate user input, you could alternatively also check for a float by stepping to it directly:

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

这篇关于如何从字符串中提取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆