Reputation: 36347
I have:
s= 'Lot Size: 1.52 acres'
I want to return a float number only (1.52)
I tried:
>>> o =[s for s in str.split('') if s.isdigit() if s=='.']
>>>
>>>o
>>>[]
How can I get this working?
Upvotes: 2
Views: 170
Reputation: 1602
You could try the following, with a singular condition and in keeping with your original format (using python 3.6.8) :)
Multiple condition syntax:
[ x for x in x.do() if 'x' in x OR/AND if x == 1]
Example:
s = 'Lot Size: 1.52 acres'
o = [s for s in s.split(' ') if '.' in s]
print(o[0])
Output:
1.52
Upvotes: 2
Reputation: 7859
Another way to do it is by using regular expressions:
import re
s='Lot Size: 1.52 acres'
result = float(re.findall("[0-9]+\.[0-9]+", s)[0])
print(result)
This will give you:
1.52
Or, in case you want a list of floats as a result:
result = list(map(float,(re.findall("[0-9]+\.[0-9]+", s))))
Upvotes: 2
Reputation: 49920
This will assign to o
a list of the "words" in msg
that can be interpreted as floats:
def isFloat(n):
try:
return float(n)
except:
return None
o = list(filter(isFloat,msg.split()))
Upvotes: 5