Harry Tong
Harry Tong

Reputation: 259

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

Upvotes: 6

Views: 16358

Answers (4)

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

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

Upvotes: 9

Vinícius Figueiredo
Vinícius Figueiredo

Reputation: 6518

You can find this using regex, notice this pattern will only return the substring if it's already in float type, i.e. decimal fomatting, so something like this:

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

As you say you want only the first one:

>>> matches[0]
'1.5'

Edit: Added [+-]? to the pattern for it to recognize negative floats, as pistache recommended!

Upvotes: 5

pistache
pistache

Reputation: 6203

If you expect whitespace separated decimal floats, using str methods and removing -+.:

s = 'I would like 1.5 cookies please'
results = [t for t in s.split() 
           if t.lstrip('+-').replace('.', '', 1).isdigit()]
print(results[0])  #1.5

lstrip is used to remove the sign only on the lefthand side of the text, and the third argument to replace is used to replace only one dot in the text. The exact implementation depends on the how you expect floats to be formatted (support whitespace between sign, etc).

Upvotes: 1

denov
denov

Reputation: 12698

I would use a regex. below also checks for negative values.

import re

stringToSearch = 'I would like 1.5 cookies please'
searchPattern = re.compile(".*(-?[0-9]\.[0-9]).*")
searchMatch = searchPattern.search(stringToSearch)

if searchMatch:
    floatValue = searchMatch.group(1)
else:
    raise Exception('float not found')

You can use PyRegex to check the regex.

Upvotes: 0

Related Questions