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?
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.
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 “$.”
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.
''.join(c for c in S if c.isdigit())
It is possible with regex.
import re
...
return re.sub(r'\D', '', theString)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With