-3

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

Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
NIWAGABA
  • 11
  • 3

1 Answers1

1

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))

Jorge Nachtigall
  • 501
  • 4
  • 20
  • 1
    Why to use `re.findall()` and generate useless list if you need just first occurrence? And your expression is far from being perfect, try to launch this code with `myString = "12.5% 35.6 per month"` – Olvin Roght Mar 23 '22 at 12:47
  • @OlvinRoght you're right about de `re.findall()`, the thing is: as I said in the answer, I did the smallest code change possible in his own code (which was almost correct). And the example you provided works as expected, `myFloat` will be equals `12.5`, maybe you should test again. – Jorge Nachtigall Mar 23 '22 at 13:33
  • 1
    I'm sorry, I copied wrong sample `myString = "a12/5% per month"` – Olvin Roght Mar 23 '22 at 13:46
  • @OlvinRoght you're right, I had a typo on my regex expression. I've forgot a \ before the `.` on the expression. I Will edit the answer. – Jorge Nachtigall Mar 24 '22 at 14:24
  • Add also `\b` to not match smth like `1.2.3.4.5`. – Olvin Roght Mar 24 '22 at 16:01