Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace non-numeric characters

I need to replace non-numeric chars from a string.

For example, "8-4545-225-144" needs to be "84545225144"; "$334fdf890==-" must be "334890".

How can I do this?

like image 985
mRt Avatar asked Sep 04 '10 16:09

mRt


People also ask

How do I remove non-numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

What is an example of a non-numeric character?

Any character which is not a number (numeric) is called non-numeric character. These could be alphabets and other symbols from the mathematical world. A letter, like “A, “B,” or “C.” A symbol like “&,” “@”, or “$.”

How do you replace a non-numeric character in Python?

sub() method to remove all non-numeric characters from a string, e.g. result = re. sub(r'[^0-9]', '', my_str) . The re. sub() method will remove all non-numeric characters from the string by replacing them with empty strings.


2 Answers

''.join(c for c in S if c.isdigit())
like image 95
Ignacio Vazquez-Abrams Avatar answered Oct 14 '22 17:10

Ignacio Vazquez-Abrams


It is possible with regex.

import re

...

return re.sub(r'\D', '', theString)
like image 35
kennytm Avatar answered Oct 14 '22 18:10

kennytm