html.escape
Five replacements, & first: the three markup characters always, both quote characters unless quote=False. Non-ASCII text, newlines and everything else pass through untouched.
Demo
import html html.escape('<a href="/x">Tom & Jerry</a>')
Every & is replaced first, then < and >, then the two quote characters — so the output of escape() can never contain a bare markup character, and the double quote in the breakout attempt can no longer end the value="..." attribute. The apostrophe becomes the hex reference ', not a named one. Already-escaped input gets its & escaped again: escape() cannot tell text from markup.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| s | str | yes | The text to escape. Must be a str — bytes and numbers fail (convert with str() first). |
| quote | bool | no (True) | Also replace " with " and ' with '. Keep it True for attribute values; False is fine for element content. |
Return value
str — A new string with the special characters replaced; everything else unchanged.
Common patterns
import html rows = "".join(f"<li>{html.escape(name)}</li>" for name in names)
import html cell = html.escape(str(value))
import html def render(template, **values): return template.format(**{k: html.escape(str(v)) for k, v in values.items()}) render("<p>{name}</p>", name="<b>x</b>")
Examples
Pitfalls
import html html.escape('<b>')
import html html.escape('<b>')
import html v = html.escape('x" onclick="go()', quote=False) f'<p title="{v}">'
import html v = html.escape('x" onclick="go()') f'<p title="{v}">'
import html html.escape(b'a < b')
import html html.escape(b'a < b'.decode())
When to use
- Writing untrusted text into HTML element content or a quoted attribute
- Showing code or markup literally on a web page
- Values inside <script> or <style> — escaping does not make them safe there
- URLs in href/src → validate the scheme, and use urllib.parse.quote for query values
- Whole pages → a template engine that auto-escapes (Jinja2, Django)
Notes
FAQ
Five: & < > always, plus " and ' when quote is true (the default). The double quote becomes the named reference quot and the apostrophe the hex reference '. Nothing else changes — accented letters and emoji are left as they are, which is correct for a UTF-8 page.