Vincent
Vincent

Reputation: 1604

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?

Upvotes: 5

Views: 9393

Answers (2)

Lemayzeur
Lemayzeur

Reputation: 8525

If you want get the output with ".", you can try this:

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

test

'30.0'

Upvotes: 0

Alexander
Alexander

Reputation: 109546

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'

Upvotes: 6

Related Questions