How to Escape HTML in Python

This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.

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

Python code

11 lines
Python 3.9+
import html

def escape_user_input(user_input: str) -> str:
    """Escape HTML-sensitive characters for safe display."""
    return html.escape(user_input)

if __name__ == "__main__":
    sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
    safe_output = escape_user_input(sample_user_input)
    print("Original:", sample_user_input)
    print("Escaped: ", safe_output)

Output

stdout
Original: <script>alert("XSS")</script> & 'quotes'
Escaped:  &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt; &amp; &#x27;quotes&#x27;

How it works

The html.escape function converts special HTML characters like <, >, &, and ' into their corresponding HTML entities. This prevents the browser from interpreting user input as markup. The default behavior escapes quotes as well, which is important for attribute values. Using this utility is a straightforward way to mitigate XSS vulnerabilities when embedding user-generated content in web pages.

Common mistakes

  • Using `html.escape` on already escaped input, causing double-encoding.
  • Forgetting that the default `quote=True` escapes both single and double quotes, which may be overkill.
  • Applying `html.escape` to entire HTML templates instead of just dynamic user input.
  • Not escaping output when using frameworks that auto-escape, leading to inconsistent behavior.

Variations

  1. Use `html.escape(user_input, quote=False)` if you want to keep quotes unescaped.
  2. Use `markupsafe.escape()` (from Flask) when working in a web framework for additional context-aware escaping.

Real-world use cases

  • Sanitizing user-submitted comments before rendering them in a web page to prevent script injection.
  • Encoding form field values in HTML attributes so that quote characters don't break the markup.
  • Preparing data for email templates that include user-provided names or 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.