如何在字符串中查找浮点数 - Python?

Har*_*ong 2 python floating-point python-3.x

我想找到使用Python 3出现在字符串中的第一个浮点数.

我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们不适合我的情况.

一个示例字符串

I would like 1.5 cookies please

Bub*_*Gut 5

我很确定这是一个更优雅的解决方案,但这个解决方案适用于您的特定情况:

s = 'I would like 1.5 cookies please'

for i in s.split():
    try:
        #trying to convert i to float
        result = float(i)
        #break the loop if i is the first string that's successfully converted
        break
    except:
        continue

print(result) #1.5
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 这完全回答了这个问题,但对于用户对"浮动"的定义可能有点过于宽泛.尝试使用`s ="使用3个cookie时无限更好."`例如:) (2认同)

Vin*_*iar 5

您可以使用regex找到它,注意此模式只会返回子字符串,如果它已经是float类型,即十进制格式,所以像这样:

>>> import re
>>> matches = re.findall("[+-]?\d+\.\d+", "I would like 1.5 cookies please")
Run Code Online (Sandbox Code Playgroud)

正如你所说,你只想要第一个:

>>> matches[0]
'1.5'
Run Code Online (Sandbox Code Playgroud)

编辑:添加[+-]?到模式中以识别负浮点数,如开心果推荐的那样!