Palavras-chave: HTML, escape, escapar, html_escape, htmlspecialchars, htmlentities

Funcões rápidas para escapar e desescapar caracteres especiais HTML (<, & etc)

from htmlentitydefs import codepoint2name as cp2nm, entitydefs as nm2cp
import re

def htmlescape(texto):
    return "".join([cp2nm.has_key(ord(x)) and
                   "&%s;"%cp2nm[ord(x)] or x for x in texto])

def htmlunescape(texto):
    return "".join([(x.startswith("&") and
                     x.endswith(";") and
                     nm2cp.has_key(x[1:-1]))
                    and nm2cp[x[1:-1]] or x
                   for x in re.split('(&\\\\w+;)', texto)])

Exemplo:

>>> htmlescape("a > x && y < 0")
'a &gt; x &amp;&amp; y &lt; 0'
>>> htmlunescape(htmlescape("a > x && y < 0"))
'a > x && y < 0'

Veja esta dica em Ruby.