This post will discuss how to remove non-alphanumeric characters from a string in Python.

1. Using regular expressions

A simple solution is to use regular expressions for removing non-alphanumeric characters from a string. The idea is to use the special character \W, which matches any character which is not a word character.

Download  Run Code

 
The \W is equivalent of [^a-zA-Z0-9_], which excludes all numbers and letters along with underscores. If you need to remove underscores as well, you can do like:

Download  Run Code

 
If the expression is used several times in a single program, you should compile and save the resulting regular expression object for reuse.

Download  Run Code

2. Using isalnum() function

Another option is to filter the string that matches with the isalnum() function. It returns true if all characters in the string are alphanumeric, false otherwise.

Download  Run Code

 
This is equivalent to:

Download  Run Code

That’s all about removing non-alphanumeric characters from a string in Python.

 
Also See:

Remove specific characters from a Python string

Remove Punctuations from a Python string