I have a string containing a string and word, I want to extract the first float the string.
myString = 12.5% per month
myFloat= [float(s) for s in re.findall(r'\b\d+\b', myString )][0]
I want to have 12.5
as myFloat
.
Thank you
I have a string containing a string and word, I want to extract the first float the string.
myString = 12.5% per month
myFloat= [float(s) for s in re.findall(r'\b\d+\b', myString )][0]
I want to have 12.5
as myFloat
.
Thank you
To not change your code completly:
import re
myString = "12.5% 35.6 per month"
myFloat= [float(s) for s in re.findall(r'[0-9]+\.[0-9]+', myString )][0]
All I've changed is the regex expression to r'[0-9]+\.[0-9]+'
.
But, as Oliver pointed in his comment, you dont need to use re.findall
to get the first occurrence.
You can simply: myFloat= float(re.search(r'[0-9]+\.[0-9]+', myString).group(0))