DevToolsForYou

HTML Escape Tool in Python — Code Examples

HTML Escape Tool in PythonUse the online tool →

HTML escaping converts special characters like <, >, &, and " into their HTML entity equivalents (&lt;, &gt;, &amp;, &quot;) to prevent XSS attacks and ensure correct rendering. Here is how to escape and unescape HTML in each language.

Python's standard library includes the html module with html.escape and html.unescape. No third-party packages needed.

Python 3
import html

raw = '<script>alert("xss")</script> & "quotes"'

# Escape (quote=True is the default — also escapes " and ')
escaped = html.escape(raw)
print(escaped)
# &lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt; &amp; &quot;quotes&quot;

# Escape but leave quotes untouched (for use inside HTML tag text, not attributes)
escaped_no_quotes = html.escape(raw, quote=False)
print(escaped_no_quotes)
# &lt;script&gt;alert("xss")&lt;/script&gt; &amp; "quotes"

# Unescape HTML entities back to raw characters
unescaped = html.unescape("&lt;b&gt;Hello&lt;/b&gt; &amp; &quot;world&quot;")
print(unescaped)  # <b>Hello</b> & "world"
Notes & gotchas
  • html.escape with quote=True (default) also escapes double quotes — use this when inserting into HTML attributes.
  • html.unescape handles named (&amp;), decimal (&#38;), and hex (&#x26;) entities.
  • In Jinja2 / Django templates, use the |e filter or enable autoescape — don't manually call html.escape in templates.
Try it in your browser

Need to html escape/unescape without writing code? The HTML Escape Tool runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open HTML Escape/Unescape
HTML Escape Tool in other languages