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>")
'<hello&goodbye>'
For other non-ASCII characters:
>>> "Übeltäter".encode("ascii", "xmlcharrefreplace")
b'Übeltäter'
Of course, if necessary, you can combine the two:
>>> cgi.escape("<Übeltäter>").encode("ascii", "xmlcharrefreplace")
b'<Übeltäter>'
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 `<` `>` or will I have to write my own conversion routine???