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.
Code
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 = "<script>alert(1)</script>"
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
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.