Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Convert string-numeric to float

I have the following string numeric values, and need to keep only the digit and decimals. I just can't find a right regular expression for this.

s = [
      "12.45-280", # need to convert to 12.45280
      "A10.4B2", # need to convert to 10.42
]
like image 314
user1187968 Avatar asked Jul 24 '26 11:07

user1187968


1 Answers

You can also remove all non-digits and non-dot characters, then convert the result to float:

In [1]: import re
In [2]: s = [
   ...:       "12.45-280", # need to convert to 12.45280
   ...:       "A10.4B2", # need to convert to 10.42
   ...: ]

In [3]: for item in s:
   ...:     print(float(re.sub(r"[^0-9.]", "", item)))
   ...:     
12.4528
10.42

Here [^0-9.] would match any character except a digit or a literal dot.

like image 84
alecxe Avatar answered Jul 26 '26 00:07

alecxe