Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a float in a string - Python?

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

like image 695
Harry Tong Avatar asked Dec 11 '22 10:12

Harry Tong


1 Answers

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
like image 136
Bubble Bubble Bubble Gut Avatar answered Dec 16 '22 13:12

Bubble Bubble Bubble Gut