How to Escape HTML in Python?

Python Tutorials

Summary: In this tutorial, you will learn to escape HTML code using the Python programming language.

Escaping HTML replaces HTML-reserved characters in an input string. For example, escaping <body> results in &lt;body&gt;.

It is done to ensure that the text is displayed as a plain text rather than as an HTML element or as code.

If there is a possibility that the text might contain HTML tags or symbols, it is best to transform them into plain text by escaping them.

In Python, we can easily escape HTML using the html.escape() method.

Use html.escape() to Escape HTML

import html 

escape_html = html.escape("Some text containing <body> tag")


Output: Some text containing &lt;body&gt; tag

As you can see, the string is escaped. Now if you display this text in a HTML file, it will not get interpreted as an HTML element.

Leave a Reply

Your email address will not be published. Required fields are marked *