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 there
module 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 URL using Python regex?
- How to replace all using Python regex?
- How to match a year with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a hex number with regex in Python?
- How to use word boundaries in Python Regex?
- How to match a UUID using Python regex?
- How to match zero or one occurence in Python regex?
- How to ignore case in Python regex?
- How to match a URL path using Python regex?
See more codes...