如何从不同Python平台的用户输入中替换一些特殊字符

时间:2017-07-17 05:03:39

标签: python escaping

我需要使用Python从不同平台(即Linux和Windows)的用户输入中替换一些特殊字符。我在下面解释我的代码。

if request.method == 'POST':
        rname1 = request.POST.get('react')

这里我通过post方法获取用户输入。我需要从用户输入中删除以下字符(如果有的话)。

1- Escape or filter special characters for windows,   ( ) < >  * ‘  = ? ; [ ] ^ ~ ! . ” % @ / \ : + , ` 

2- Escape or filter special characters for Linux, { }  ( ) < >  * ‘  = ? ; [ ]  $ – # ~ ! . ” %  / \ : + , `

上面给出了特殊字符。在这里,我需要删除Linux和Windows。

1 个答案:

答案 0 :(得分:0)

Python字符串具有内置方法translate,用于替换/删除字符。您需要构建转换表,然后调用该函数。

import sys
if "win" in sys.platform:
    special = """( ) < >  * ‘  = ? ; [ ] ^ ~ ! . ” % @ / \ : + , `""".split()
else:
    special = """{ }  ( ) < >  * ‘  = ? ; [ ]  $ – # ~ ! . ” %  / \ : + , `""".split()

trans_dict = {character: None for character in special}
trans_table = str.maketrans(trans_dict)
print("Lo+=r?e~~m ipsum dol;or sit!! amet, consectet..ur ad%".translate(trans_table))

将打印Lorem ipsum dolor sit amet consectetur ad

如果您想使用替换字符而不是删除,请将上面的None替换为该字符。你可以建立一个具有特定替换的翻译表,`{&#34; a&#34;:&#34; m&#34;,&#34; b&#34;:&#34; n&#34;,.. }

编辑:上面的代码段确实在Python3中。在Python2(TiO)中,easier to delete characters

>>> import sys
>>> import string
>>> if "win" in sys.platform:
...    special = """()<>*'=?;[]^~!%@/\:=,`"""
... else:
...    special = """{}()<>*'=?;[]$-#~!."%/\:+"""
...
>>> s = "Lo+r?e~~/\#<>m ips()u;m"
>>> string.translate(s, None, special)
'Lorem ipsum'

请注意,我已将替换为',同样将替换为"因为我认为您只处理ascii字符串。