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")

print(escape_html)

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.

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.

Leave a Reply