python-regexHow to remove numbers from a string using Python regex?
Using Python regex, numbers can be removed from a string by using the re.sub()
function. This function takes two arguments, the pattern to be matched and the replacement string. The pattern can be specified using the \d
character class, which matches any digit.
import re
string = "This is a string with 123 numbers"
result = re.sub(r'\d+', '', string)
print(result)
Output example
This is a string with numbers
The code above consists of the following parts:
import re
: This imports there
module, which provides functions for working with regular expressions.string = "This is a string with 123 numbers"
: This creates a string variable containing the string to be processed.result = re.sub(r'\d+', '', string)
: This uses there.sub()
function to replace any digits in the string with an empty string.print(result)
: This prints the result of the substitution.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to perform a zero length match with Python Regex?
- How to match a UUID using Python regex?
- How to match a year with Python Regex?
- How to match a URL using Python regex?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
See more codes...