How to Unescape HTML Entities in Python

Convert HTML entities like & and < back to their literal characters using the standard library html module.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

12 lines
Python 3.9+
import html

def unescape_html_entities(text: str) -> str:
    """Convert HTML entities like & to their character equivalents."""
    return html.unescape(text)

if __name__ == "__main__":
    sample = "Tom & Jerry <cartoon> "classic" 'fun' © 2024"
    result = unescape_html_entities(sample)
    print(f"Input:  {sample}")
    print(f"Output: {result}")
    print(f"Unescaped: {html.unescape('<div>Hello & Welcome</div>')}")

Output

stdout
Input:  Tom & Jerry <cartoon> "classic" 'fun' © 2024
Output: Tom & Jerry <cartoon> "classic" 'fun' © 2024
Unescaped: <div>Hello & Welcome</div>

How it works

The html.unescape function handles all named HTML character references defined in the HTML standard, including &amp;, &lt;, &gt;, &quot;, &apos;, and &copy;. It also converts numeric character references like &#169; to their corresponding Unicode characters. Because both the transformation and rendering are handled by a single built-in function, this approach is reliable and requires no external dependencies. The function runs in linear time relative to input length and safely frees strings that contain no entities by returning them unchanged.

Common mistakes

  • Using `html.escape` instead of `html.unescape` for converting entities back to characters
  • Assuming only `&amp;` needs handling — forgetting `&lt;`, `&gt;`, `&quot;`, and numeric references
  • Trying to manually replace entities with `str.replace` calls in a loop, which is error-prone and brittle

Variations

  1. Use `re.sub` with a custom mapping for very limited entity subsets, though the stdlib approach is preferred
  2. For XML-specific unescaping, use `xml.sax.saxutils.unescape` which only handles `&amp;`, `&lt;`, `&gt;`

Real-world use cases

  • Cleaning scraped web page content before displaying it in a desktop or CLI tool.
  • Normalizing user-generated content that was double-escaped when saved to a database.
  • Converting HTML entities in email subject lines or notification text before sending out messages.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.