How to Remove Non-Numeric Characters from a String in Python?

Estimated read time 1 min read

You can remove non-numeric characters from a string in Python using regular expressions and the re module. Here’s an example:

import re

s = '123-456-7890'
new_s = re.sub(r'\D', '', s)
print(new_s) # Output: '1234567890'

In this example, we have a string (s) that contains numeric and non-numeric characters, including spaces, letters, and punctuation. We want to remove all non-numeric characters from the string. We achieve this by using the sub() method from the re module, which replaces all occurrences of a regular expression pattern with a specified string. The regular expression pattern \D matches any character that is not a digit. The replacement string is an empty string, which removes all non-numeric characters from the string. The resulting string contains only numeric characters.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply