Computer >> Computer tutorials >  >> Programming >> Python

How to remove all special characters, punctuation and spaces from a string in Python?


To remove all special characters, punctuation and spaces from string, iterate over the string and filter out all non alpha numeric characters. For example:

>>> string = "Hello $#! People   Whitespace 7331"
>>> ''.join(e for e in string if e.isalnum())
'HelloPeopleWhitespace7331'

Regular expressions can also be used to remove any non alphanumeric characters. re.sub(regex, string_to_replace_with, original_string) will substitute all non alphanumeric characters with empty string. For example,

>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', "Hello $#! People   Whitespace 7331")
'HelloPeopleWhitespace7331'