html.escape and html.unescape
html.escape(s, quote=True)
html.unescape(s)escape converts &, <, >, and, by default, quotes. unescape decodes character references back to Unicode characters.
| Parameter | Description |
|---|---|
s | A str to escape or unescape. Pass a string, not bytes. |
quote | If true (the default), also replace " with " and ' with '. If false, quotes are left unchanged. |
Returns: A new str. The original string is not modified.
- In Python 3.13, a single quote is escaped as ' when quote=True.
import html
sample = '<p class="note">A & B</p>'
print(html.escape(sample))
print(html.escape(sample, quote=False))
print(html.escape("it's ok"))
print(html.unescape('<p class="note">A & B</p>'))Expected output
<p class="note">A & B</p>
<p class="note">A & B</p>
it's ok
<p class="note">A & B</p>
Related: HTML escape tool, HTML entity encoder, str methods