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

PythonServer Side ProgrammingProgramming

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'
raja
Published on 14-Dec-2017 09:56:11
Advertisements