python: convert to HTML special characters

html, python

Solution

If you're only concerned about critical special characters like `&`, `<` and `>`:

>>> import cgi
>>> cgi.escape("<hello&goodbye>")
'&lt;hello&amp;goodbye&gt;'

For other non-ASCII characters:

>>> "Übeltäter".encode("ascii", "xmlcharrefreplace")
b'&#220;belt&#228;ter'

Of course, if necessary, you can combine the two:

>>> cgi.escape("<Übeltäter>").encode("ascii", "xmlcharrefreplace")
b'&lt;&#220;belt&#228;ter&gt;'

Problem

Possible Duplicate: Replace html entities with the corresponding utf-8 characters in Python 2.6 What's the easiest way to escape HTML in Python? There is a way to easily convert a string to a HTML string, e.g. with chars like <, > replaced by `&lt;` `&gt;` or will I have to write my own conversion routine???

Original source

Related problems