html.escape Renders Untrusted Text Safe

html.escape turns angle brackets, ampersands, and quotes into entities so untrusted text stays inert, and unescape reverses the mapping on read-back.

PythonSecurity Boundaries

Code

pythonsnippet
16 lines
import html

# Untrusted text goes into an HTML page: escape it so markup stays inert.
comment = 'Use <b>bold</b> & "quotes" and it\'s 5 < 10'
print(html.escape(comment))

# quote=False leaves quotes alone for text nodes, still escapes angle brackets.
print(html.escape(comment, quote=False))

# unescape reverses the mapping for text pulled back out of HTML.
encoded = "&lt;script&gt;alert(1)&lt;/script&gt;"
print(html.unescape(encoded))

# Escape attribute values too, or a quote character breaks out of the tag.
value = 'name="XSS" onload="alert(1)"'
print(f'<input value="{html.escape(value)}">')

What the code does

Top-level bindings comment, encoded, value hold the demo state — nothing sits inside a function scope.

What to watch for

  • Dependency check: html — not built-in, must be present in the project.

Using it

The demo output is labeled (<input value=), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `html` must be present in the project or the import fails at load time.