Python Glossary Русский

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 &amp; into &amp;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>'))  # → &lt;b&gt;Tom &amp; &quot;Jerry&quot;&lt;/b&gt;
print(html.escape("it's"))  # → it&#x27;s
print(html.escape('"x"', quote=False))  # → "x"
import html
once = html.escape('a & b')
print(once)  # → a &amp; b
print(html.escape(once))  # → a &amp;amp; b — двойное экранирование

See also

Open in the full glossarydocs.python.orgReport an inaccuracy