Har*_*ong 2 python floating-point python-3.x
我想找到使用Python 3出现在字符串中的第一个浮点数.
我查看了其他类似的问题,但我无法理解它们,当我尝试实施它们时,它们不适合我的情况.
一个示例字符串
I would like 1.5 cookies please
我很确定这是一个更优雅的解决方案,但这个解决方案适用于您的特定情况:
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)
希望能帮助到你!
您可以使用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)
编辑:添加[+-]?到模式中以识别负浮点数,如开心果推荐的那样!
| 归档时间: |
|
| 查看次数: |
3934 次 |
| 最近记录: |