码迷,mamicode.com
首页 > 编程语言 > 详细

Python类似PHP的htmlspeialchars()过滤字符串函数

时间:2016-08-03 10:18:30      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:

1:使用cgi模块的escape()函数

>>> import cgi
>>> stra = <foo>\nfoo\t"bar"
>>> resa = cgi.escape(stra)
>>> print(resa)
&lt;foo&gt;
foo    "bar"
>>> strb = "<foo>\nfoo\t‘bar‘"
>>> resb = cgi.escape(strb)
>>> print(resb)
&lt;foo&gt;
foo    bar

可见字符串中的单引号和双引号没有转义为字符实体,查看文档

escape(s, quote=None)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

可知,如果给一个quote=True,那么双引号会被转义,但是单引号却不会;

resaa = cgi.escape(stra,True)
>>> print(resaa)
&lt;foo&gt;
foo    &quot;bar&quot;    #这里转义了双引号
>>> resbb = cgi.escape(strb,True)
>>> print(resbb)
&lt;foo&gt;
foo    bar‘    #这里却没有转义

 

2:使用html模块的escape方法

>>> import html
>>> stra = <foo>\nfoo\t"bar"
>>> resa = html.escape(stra)
>>> print(resa)
&lt;foo&gt;
foo    &quot;bar&quot;    #这里做了转义处理  
>>> strb = "<foo>\nfoo\t‘bar‘"
>>> resb = html.escape(strb)
>>> print(resb)
&lt;foo&gt;
foo    &#x27;bar&#x27;  #这里做了转义处理 

html模块的escape方法默认是处理单引号和双引号的,文档:

escape(s, quote=True)
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true (the default), the quotation mark
    characters, both double quote (") and single quote (‘) characters are also
    translated.

Python类似PHP的htmlspeialchars()过滤字符串函数

标签:

原文地址:http://www.cnblogs.com/mrylong/p/5731607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!