Python / 从字符串中删除特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25991612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:18  来源:igfitidea点击:

Python / Remove special character from string

python

提问by Or Smith

I'm writing server side in python.

我正在用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 replacecommand), but I also want to get rid of the special character: "?".

我想去掉空格(为此我使用replace命令),但我也想去掉特殊字符:“?”。

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

如何使用 python 命令摆脱这个字符(和其他奇怪的字符,不是-, _, *, .)?

采纳答案by Daniel Roseman

A regex would be good here:

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

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

回答by Bartosz Marcinkowski

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

回答by enrico.bacis

I would use a regex like this:

我会使用这样的正则表达式:

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