django:
from django.utils.html import escape
print escape('Q & A')
python标准库,3.x为:html.entities,python2.x里对应的是htmlentitydefs模块
3.x:
>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'
2.x
import htmlentitydefs
print htmlentitydefs.codepoint2name[ord('&')]
amp
反向解码,即类似php的htmlspecialchars_decode()函数
print chr(htmlentitydefs.name2codepoint['amp'])
&
参考: Is there a Python equivalent to the PHP function htmlspecialchars()? – Stack Overflow