Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the first float from a string in python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]+'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading