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

新手上路,请多包涵

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

我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们对我的情况不起作用。

一个示例字符串是

I would like 1.5 cookies please

原文由 Harry Tong 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 537
1 个回答

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

 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

原文由 Bubble Bubble Bubble Gut 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题