Differences between revisions 3 and 4
Revision 3 as of 2005-05-01 07:54:09
Size: 679
Editor: aaron
Comment:
Revision 4 as of 2005-06-10 16:35:17
Size: 981
Editor: 63
Comment: table for unquoting entities?
Deletions are marked like this. Additions are marked like this.
Line 18: Line 18:
html_escape_table = {
    "&": "&",
    '"': """,
    "'": "'",
    ">": ">",
    "<": "&lt;" }
html_escape_table = \
    {"&": "&amp;",
  '"': "&quot;",
     "'": "&apos;",
  ">": "&gt;",
     "<": "&lt;"}
Line 27: Line 27:
    l=[]     L=[]
Line 29: Line 29:
        l.append( html_escape_table.get(c,c) )
    return "".join(l)
        L.append(html_escape_table.get(c,c))
    return "".join(L)
Line 35: Line 35:
  (none yet) LionKimbro: Is there anything in the standard library for going the other way? Is there something where you can give it "&amp;" and get back "&"? Perhaps in the XML libraries? I looked, but did not see anything. DOM, SAX- wouldn't be there. Not exactly XML-RPC either. Anyone know? [[Date(2005-06-10T16:35:16Z)]]

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 characters 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     """Produce entities within text."""
  10     L=[]
  11     for c in text:
  12         L.append(html_escape_table.get(c,c))
  13     return "".join(L)

Discussion

LionKimbro: Is there anything in the standard library for going the other way? Is there something where you can give it "&" and get back "&"? Perhaps in the XML libraries? I looked, but did not see anything. DOM, SAX- wouldn't be there. Not exactly XML-RPC either. Anyone know? Date(2005-06-10T16:35:16Z)

EscapingHtml (last edited 2016-11-19 12:13:41 by OleskandrGavenko)

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