How to Unescape HTML Entities in Python
Convert HTML entities like & and < back to their literal characters using the standard library html module.
Python code
12 linesimport 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
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 &, <, >, ", ', and ©. It also converts numeric character references like © 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 `&` needs handling — forgetting `<`, `>`, `"`, and numeric references
- Trying to manually replace entities with `str.replace` calls in a loop, which is error-prone and brittle
Variations
- Use `re.sub` with a custom mapping for very limited entity subsets, though the stdlib approach is preferred
- For XML-specific unescaping, use `xml.sax.saxutils.unescape` which only handles `&`, `<`, `>`
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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.