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

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

问题描述

我有许多类似于 Current Level:13.4 db。的字符串,我只想提取浮点数。我说浮动,而不是小数,因为它有时是整体。 RegEx可以做到这一点,或者有更好的方法吗?

解决方案

>

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

就足够了。

一个更健壮的版本可能是:

 >>> re.findall(r[ -  +]?\ d * \.\\\d\\ | \d +,当前级别:-13.2 db或14.2或3)
['-13.2', '14.2','3']

如果您想验证用户输入,

  user_input =当前级别:1e100 db
for user_input .split():
try:
#如果成功,你有(首先)浮动
打印浮动(令牌),是浮动
除了ValueError:
打印令牌,是别的东西

#=>将打印...

#当前是别的
#级别:是别的
#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天全站免登陆