Revision 1 as of 2004-06-01 23:16:12

Clear message

Escaping HTML

The cgi module that comes with Python has an escape function:

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

However, it doesn't escape anything beyond &, <, and >.

Here's a small snippet that will let you escape those as well:

   1 html_escape_table = {
   2     "&": "&amp;",
   3     '"': "&quot;",
   4     "'": "&apos;",
   5     ">": "&gt;",
   6     "<": "&lt;" }
   7 
   8 def html_escape( text ):
   9     l=[]
  10     for c in text:
  11         l.append( html_escape_table.get(c,c) )
  12     return "".join(l)

Discussion

Unable to edit the page? See the FrontPage for instructions.