1:使用cgi模块的escape()函数
>>> import cgi >>> stra = ‘<foo>\nfoo\t"bar"‘ >>> resa = cgi.escape(stra) >>> print(resa) <foo> foo "bar" >>> strb = "<foo>\nfoo\t‘bar‘" >>> resb = cgi.escape(strb) >>> print(resb) <foo> 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) <foo> foo "bar" #这里转义了双引号 >>> resbb = cgi.escape(strb,True) >>> print(resbb) <foo> foo ‘bar‘ #这里却没有转义
2:使用html模块的escape方法
>>> import html >>> stra = ‘<foo>\nfoo\t"bar"‘ >>> resa = html.escape(stra) >>> print(resa) <foo> foo "bar" #这里做了转义处理 >>> strb = "<foo>\nfoo\t‘bar‘" >>> resb = html.escape(strb) >>> print(resb) <foo> foo 'bar' #这里做了转义处理
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.
时间: 2024-11-06 17:24:09