Remove all special characters, punctuation and spaces from string


Question

I need to remove all special characters, punctuation and spaces from a string so that I only have letters and numbers.

1
185
6/11/2015 4:20:45 AM

Accepted Answer

This can be done without regex:

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

You can use str.isalnum:

S.isalnum() -> bool

Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.

If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.

294
4/30/2011 8:07:47 PM

Here is a regex to match a string of characters that are not a letters or numbers:

[^A-Za-z0-9]+

Here is the Python command to do a regex substitution:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon