简体   繁体   中英

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?

正则表达式在这里会很好:

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

I would use a regex like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM