9951 explained code solutions for 126 technologies


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 the re module which provides functions for working with regular expressions
  • string = 'This is a string with special characters!': creates a string with special characters
  • string = re.sub('[^A-Za-z0-9]+', '', string): uses the re.sub() function to replace all characters that are not letters or numbers with an empty string
  • print(string): prints the modified string

Helpful links

Edit this code on GitHub