Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - extract numbers and commas from string (with re.sub)

I have the following string (Python) :

test = "    +30,0 EUR abcdefgh   "

I want to remove everything but numbers and comma ",".

Expected result: "30.0"

So based on re doc I tried :

test = re.sub('^[0-9,]', "", test)

Output is:

"    +30,0 EUR abcdefgh   "

Nothing happened. Why?

like image 317
Vincent Avatar asked Sep 25 '22 16:09

Vincent


1 Answers

The ^ needs to go inside the brackets.

>>> re.sub('[^0-9,]', "", test)
'30,0'

To change the comma to a decimal:

>>> '30,0're.sub('[^0-9,]', "", test).replace(",", ".")
'30.0'
like image 78
Alexander Avatar answered Oct 03 '22 06:10

Alexander