Skip to main content

How to remove all special characters from a string in Python

How to remove all special characters from a string in Python.

Here's a step-by-step tutorial on how to remove all special characters from a string in Python.

Step 1: Import the necessary modules

To begin, you need to import the re module, which provides regular expression pattern matching operations.

import re

Step 2: Define the string

Next, define the string from which you want to remove the special characters.

string = "Hello! @World#"

Step 3: Use regular expressions to remove special characters

Regular expressions can be used to match and remove specific patterns from a string. In this case, we can use a regular expression pattern to match any character that is not an alphabetic or numeric character.

string = re.sub('[^A-Za-z0-9]+', '', string)

Here's what this line does:

  • re.sub() is a function that performs a search and replace operation using regular expressions.
  • '[^A-Za-z0-9]+' is a regular expression pattern that matches any character that is not an alphabetic or numeric character.
  • '' is the replacement string, which is an empty string. This means that any matched characters will be removed from the string.

Step 4: Print the modified string

Finally, you can print the modified string without the special characters.

print(string)

The complete code would look like this:

import re

string = "Hello! @World#"
string = re.sub('[^A-Za-z0-9]+', '', string)
print(string)

Output:

HelloWorld

That's it! You have successfully removed all the special characters from the string.