html
HTML escaping and unescaping library, matching Python’s html module.
Available Functions
| Function | Description |
|---|---|
escape(s) |
Escape HTML special characters in a string. |
unescape(s) |
Unescape HTML entities in a string. |
Functions
escape(s)
Escapes HTML special characters in a string so it can be safely embedded in HTML. Converts & to &, < to <, > to >, " to ", and ' to '.
Parameters:
s(str): String to escape.
Returns: str: the escaped string.
import html
safe = html.escape("<script>alert('xss')</script>")
print(safe) # "<script>alert('xss')</script>"unescape(s)
Unescapes HTML entities in a string, converting them back to their corresponding characters. Handles named entities (<, >, &, ", ') and numeric entities (<, <).
Parameters:
s(str): String with HTML entities to unescape.
Returns: str: the unescaped string.
import html
text = html.unescape("<script>")
print(text) # "<script>"Examples
Sanitize User Input
import html
user_input = "<script>alert('xss')</script>"
safe_output = html.escape(user_input)
print(safe_output)
# Output: <script>alert('xss')</script>Build Safe HTML
import html
def create_element(tag, content):
safe_content = html.escape(content)
return "<" + tag + ">" + safe_content + "</" + tag + ">"
print(create_element("p", "Hello <world>"))
# Output: <p>Hello <world></p>Process HTML Entities
import html
# From API response
encoded = "Tom & Jerry"
decoded = html.unescape(encoded)
print(decoded) # "Tom & Jerry"Roundtrip Conversion
import html
original = '<div class="test">Content</div>'
escaped = html.escape(original)
restored = html.unescape(escaped)
print(original == restored) # TruePython Compatibility
unescape(s)- ✅ Compatibleescape(s)- ⚠️ Mostly compatible. The implementation uses Go’shtml.EscapeString, which emits numeric character references for quotes ("→",'→') rather than Python’s named/hex forms ("→",'→'). The escaped output is semantically equivalent but not byte-identical.
Note: Python’s html.escape() has an optional quote parameter (default True) which is not implemented. This implementation always escapes quotes.
See Also
- html.parser - HTML parsing for extracting tags and data
- string - String constants for character classification
- regex - Regular expressions for text processing