Possible Duplicate:
Replace html entities with the corresponding utf-8 characters in Python 2.6
What's the easiest way to escape HTML in Python?蟒蛇:转换为HTML特殊字符
有一种方法可以轻松地将字符串转换为HTML字符串,例如 与字符如<,><
>
或将我必须写我自己的转换程序?
Possible Duplicate:
Replace html entities with the corresponding utf-8 characters in Python 2.6
What's the easiest way to escape HTML in Python?蟒蛇:转换为HTML特殊字符
有一种方法可以轻松地将字符串转换为HTML字符串,例如 与字符如<,><
>
或将我必须写我自己的转换程序?
如果你只关注关键特殊字符,如&
,<
和>
:
>>> import cgi
>>> cgi.escape("<hello&goodbye>")
'<hello&goodbye>'
对于其他非ASCII字符:
>>> "Übeltäter".encode("ascii", "xmlcharrefreplace")
b'Übeltäter'
当然,如果需要,可以结合两者:
>>> cgi.escape("<Übeltäter>").encode("ascii", "xmlcharrefreplace")
b'<Übeltäter>'
>>> >>>“Übeltäter”.encode( “ascii”,“xmlcharrefreplace”)'结果为 'UnicodeDecodeError:'ascii'编解码器无法解码0位的字节0xc3:序号不在范围内(128) – brandones
请参阅http:// doc s.python.org/library/htmllib.html#module-htmlentitydefs –
@TimPietzcker:oops ...标题并没有真正的帮助;-) – vartec
我认为你需要的是所谓的“HTML转义”。这就是为什么你没有自己找到答案。 [这里是一个Stackoverflow的答案。](http://stackoverflow.com/questions/1061697/whats-the-easiest-way-to-escape-html-in-python) – tsikov