Newbie: How to convert "<" to "&lt;" ( encoding? )

Jon Ribbens jon+python-list at unequivocal.co.uk
Wed Oct 4 10:29:25 EDT 2000


Aahz Maruch <aahz at panix.com> wrote:
> >what about cgi.escape() ?
> 
> Ah, there it is.  Okay, I wasn't familiar with the cgi module.  Thanks!
> There probably should still be a generic char-to-entity routine based on
> the htmlentitydefs module, but that's lower priority.

Note that cgi.escape() should be escaping the single-quote character also,
but isn't.

I think it would be nice if string.replace could take a map as a parameter,
to do multiple replacements at once ;-).

In my CGI library I did it like this:

_html_encre = re.compile("[&<>\"']")
_html_encodes = { "&": "&", "<": "<", ">": ">", "\"": """,
                  "'": "'" }

def html_encode(input):
  return re.sub(_html_encre, lambda m: _html_encodes[m.group(0)], str(input))

(Just to prove you can do nasty one-line things in Python just as you can
in Perl ;-) )

Cheers


Jon




More information about the Python-list mailing list