Remove non-alphanumeric characters from a Python string
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.
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': input = "Welcome, User_12!!" s = re.sub(r'\W+', '', input) print(s) # WelcomeUser_12 |
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:
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': input = "Welcome, User_12!!" s = re.sub(r'[^a-zA-Z0-9]', '', input) print(s) # WelcomeUser12 |
If the expression is used several times in a single program, you should compile and save the resulting regular expression object for reuse.
|
1 2 3 4 5 6 7 8 9 10 11 |
import re if __name__ == '__main__': input = "Welcome, User_12!!" pattern = re.compile('\W') s = re.sub(pattern, '', input) print(s) # WelcomeUser_12 |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': input = "Welcome, User_12!!" s = ''.join(filter(str.isalnum, input)) print(s) # WelcomeUser12 |
This is equivalent to:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': input = "Welcome, User_12!!" s = ''.join(c for c in input if c.isalnum()) print(s) # WelcomeUser12 |
That’s all about removing non-alphanumeric characters from a string in Python.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)