Python / Remove special character from string

I am writing a server side in python.

I noticed that the client sent me one of the parameters:

"↵ tryit1.tar↵ " 

I want to get rid of the spaces (and for this I use the replace command), but I also want to get rid of the special character: "↵".

How can I get rid of this character (and other weird characters that are not - , _ , * ,.) With the python command?

+7
python
source share
3 answers

The regular expression will be useful here:

 re.sub('[^a-zA-Z0-9-_*.]', '', my_string) 
+17
source share
 >>> import string >>> my_string = "↵ tryit1.tar↵ " >>> acceptable_characters = string.letters + string.digits + "-_*." >>> filter(lambda c: c in acceptable_characters, my_string) 'tryit1.tar' 
+2
source share

I would use a regex:

 import re string = "↵ tryit1.tar↵ " print re.sub(r'[^\w.]', '', string) # tryit1.tar 
+2
source share

All Articles