Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all special characters, punctuation and spaces from string

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

like image 281
user664546 Avatar asked Apr 30 '11 17:04

user664546


People also ask

How do you remove spaces and punctuations from a string in Python?

One of the easiest ways to remove punctuation from a string in Python is to use the str. translate() method. The translate method typically takes a translation table, which we'll do using the . maketrans() method.

How do I remove all symbols from a string in Python?

Short answer: Use string. replace() .


1 Answers

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.

like image 187
user225312 Avatar answered Oct 22 '22 13:10

user225312