I want to find the first float that appears in a string using Python 3.
I looked at other similar questions but I couldn't understand them and when I tried to implement them they didn't work for my case.
An example string would be
I would like 1.5 cookies please
I'm pretty sure there's more elegant solution, but this one works for your specific case:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With