Home > Net >  How to properly convert regex string to float
How to properly convert regex string to float

Time:06-30

I have a string that I am attempting to extract, for instance, the string below, I want to extract only 3.10 but as a float so that if the number is under 3.9 I can add logic.

Here is what I have thus far

import re
x='3.10.8.10_IDNUM19191_SUITE'
m=re.search(r"([0-9] (\.[0-9] ) )", x)
m= (m.group(1))
print(m)

if m>='3.9':
  print("Number is 3.9.0 or higher")
else:
  print("Number is under 3.9.0")

I am unable to use float because it cannot convert '3.10.8.10' to a float. The regex I have pulls out 3.10.8.10 instead of 3.10

CodePudding user response:

import re
x='3.10.8.10_IDNUM19191_SUITE'
m=re.search(r"([0-9] (\.[0-9] ))", x)
m= (m.group(1))
print(m)

if float(m)>=3.9:
  print("Number is 3.9.0 or higher")
else:
  print("Number is under 3.9.0")

CodePudding user response:

The regex you have will return a string in the format aaa.bbb.ccc.ddd... where aaa, bbb, ccc, ddd are digits.

If you don't need the .ccc.ddd... part you can rewrite the regex to r"([0-9] \.[0-9] )" and the returned number will be usable by float().

  • Related