python-regexHow to remove special characters using Python regex?
Regular expressions (regex) can be used to remove special characters from a string in Python. The re.sub() function can be used to replace a pattern in a string with an empty string. The pattern can be specified using a regular expression.
For example, the following code block can be used to remove all special characters from a string:
import re
string = 'This is a string with special characters!'
string = re.sub('[^A-Za-z0-9]+', '', string)
print(string)
The output of the above code is:
Thisisastringwithspecialcharacters
The code works as follows:
import re: imports theremodule which provides functions for working with regular expressionsstring = 'This is a string with special characters!': creates a string with special charactersstring = re.sub('[^A-Za-z0-9]+', '', string): uses there.sub()function to replace all characters that are not letters or numbers with an empty stringprint(string): prints the modified string
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match digits with Python regex?
- How to perform a zero length match with Python Regex?
- How to match a year with Python Regex?
- How to make a case insensitive match with Python regex?
- How to match any symbol except a given one with Python regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match one or more occurence in Python regex?
- How to get all matches from a regex in Python?
See more codes...