def html_escape(s):
 if (s is None):
  return ''
 if (not isinstance(s, basestring)):
  if hasattr(s, '__unicode__'):
   s = unicode(s)
  else:
   s = str(s)
 s = cgi.escape(s, True)
 if isinstance(s, unicode):
  s = s.encode('ascii', 'xmlcharrefreplace')
 return s

def html_escape ( s ) : if ( s is None ) : return '' if ( not isinstance ( s , basestring ) ) : if hasattr ( s , '__unicode__' ) : s = unicode ( s ) else : s = str ( s ) s = cgi . escape ( s , True ) if isinstance ( s , unicode ) : s = s . encode ( 'ascii' , 'xmlcharrefreplace' ) return s
an html escape function that behaves the same in both python 2 and 3 .