Python 3.2+Strings (str)function
html.escape()
HTML escaping
Replaces &, <, > and (by default) quotes with HTML entities so that user text can be safely inserted into an HTML page.
Syntax
html.escape(s, quote=True)
The function is not idempotent: a second call turns & into &amp;, so escape exactly once, at the moment you insert text into markup, not when saving it to a database. With quote=False the quotes stay as they are, and such text must not go into an attribute value: a " would close it. Non-ASCII text is left untouched, and the function does not protect URLs or JavaScript code — use urllib.parse.quote and json.dumps there.
Examples
import html
print(html.escape('<b>Tom & "Jerry"</b>')) # → <b>Tom & "Jerry"</b>
print(html.escape("it's")) # → it's
print(html.escape('"x"', quote=False)) # → "x"
import html
once = html.escape('a & b')
print(once) # → a & b
print(html.escape(once)) # → a &amp; b — двойное экранирование
See also
Open in the full glossarydocs.python.orgReport an inaccuracy