Or Smith
Or Smith

Reputation: 3596

Python / Remove special character from string

I'm writing server side in python.

I noticed that the client sent me one of the parameter like this:

"↵                        tryit1.tar↵                        "

I want to get rid of spaces (and for that 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, which are not -,_,*,.) using python command?

Upvotes: 13

Views: 32691

Answers (3)

enrico.bacis
enrico.bacis

Reputation: 31484

I would use a regex like this:

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

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

A regex would be good here:

re.sub('[^a-zA-Z0-9-_*.]', '', my_string)

Upvotes: 24

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

>>> import string
>>> my_string = "↵                        tryit1.tar↵                        "
>>> acceptable_characters = string.letters + string.digits + "-_*."
>>> filter(lambda c: c in acceptable_characters, my_string)
'tryit1.tar'

Upvotes: 2

Related Questions