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 question mark in Python regex?
- How to match a plus sign in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to match one or more occurence in Python regex?
- How to match a UUID using Python regex?
- How to split using Python regex?
See more codes...