See Escaping HTML in the Python Wiki

CGI

import cgi

s = cgi.escape( """& < >""" )   # s = "&amp; &lt; &gt;"

HTML

import html


s = html.escape( """& < " ' >""" )   # s = '&amp; &lt; &quot; &#x27; &gt;'