Generate HTML with Python
Five ways to turn Python data into HTML, and how to tell which one your job needs.
Python has no single built-in way to write HTML, which is why a search for "python html" turns up five different answers. They are all reasonable. Which one fits depends on how much HTML you have and where the data comes from.
The short answer
For a small piece of HTML, an f-string with html.escape around every value is enough, and needs nothing installed:
import html
name = "Ada <[email protected]>"
print(f"<p>Hello, {html.escape(name)}</p>")
Once you have whole pages, move to a template engine or build the HTML as objects. The rest of this page goes through each option in turn.
F-strings and the escaping problem
An f-string drops the value in exactly as it is:
print(f"<p>Hello, {name}</p>")
# <p>Hello, Ada <[email protected]></p>
A browser reads <[email protected]> as a tag, so the address vanishes from the page. That is the harmless version. If name came from a form and contained a <script> tag, the browser would run it. Every value that is not your own markup has to be escaped, every time, and nothing reminds you when you forget one.
Building a list shows where it starts to strain:
drinks = ["Tea & cake", "Coffee"]
items = "".join(f"<li>{html.escape(d)}</li>" for d in drinks)
print(f"<ul>{items}</ul>")
# <ul><li>Tea & cake</li><li>Coffee</li></ul>
That is fine for a status email or a small report. It becomes hard to read at about the point where the nesting goes three levels deep.
The Python html module: what it actually does
The name suggests an HTML builder. It is not one. The standard html module has two functions:
print(html.escape('Tom & "Jerry" <b>'))
# Tom & "Jerry" <b>
print(html.unescape("café & bar"))
# café & bar
escape makes text safe to put inside HTML, including inside a quoted attribute. unescape goes the other way and turns entities back into characters.
Next to it sits html.parser, which reads HTML instead of writing it. You subclass HTMLParser and it calls your methods as it meets each tag:
from html.parser import HTMLParser
class LinkFinder(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == "a":
self.links.append(dict(attrs).get("href"))
finder = LinkFinder()
finder.feed('<p>See <a href="/https/nitro.sh/docs">the docs</a> and <a href="/https/nitro.sh/ui">Nitro UI</a>.</p>')
print(finder.links) # ['/docs', '/ui']
So the standard library can escape HTML and parse it. Nothing in it generates HTML for you.
string.Template
string.Template fills $name placeholders in a string. Its advantage over an f-string is that the HTML can live in a separate file, or come from someone who should not be writing Python:
from string import Template
page = Template("<h1>$title</h1><p>Hello, $name</p>")
print(page.substitute(title="Welcome", name=html.escape(name)))
# <h1>Welcome</h1><p>Hello, Ada <[email protected]></p>
It has no loops, no conditions, and it does not escape anything, so html.escape is still your job. The details are in Python string templates.
A Python HTML generator with loops: template engines
When pages have loops, conditions and a shared layout, the usual answer is a template engine. Jinja2 is the common choice (pip install jinja2) and is what Flask uses:
from jinja2 import Environment
env = Environment(autoescape=True)
template = env.from_string(
"<ul>{% for d in drinks %}<li>{{ d }}</li>{% endfor %}</ul>"
)
print(template.render(drinks=["Tea & cake", "Coffee"]))
With autoescape=True every value is escaped for you, which removes the biggest risk of the f-string approach. Templates are ordinary HTML files, so a designer can edit them. The cost is a second small language to learn, and logic that ends up split between Python and template files.
A Python HTML library that builds it as objects
The last option skips strings altogether. Each element is a Python object, children are arguments, and the library writes the tags. Nitro UI works this way (pip install nitro-ui):
from nitro_ui import Div, H1, ListItem, Paragraph, Strong, UnorderedList
card = Div(
H1("Menu"),
UnorderedList(*[ListItem(d) for d in drinks]),
Paragraph("Hello, ", Strong(name)),
cls="card",
)
print(card.render())
# <div class="card"><h1>Menu</h1><ul><li>Tea & cake</li><li>Coffee</li></ul><p>Hello, <strong>Ada <[email protected]></strong></p></div>
Text is escaped automatically, tags cannot be left unclosed, and a loop is a list comprehension. A reusable piece of page is a function that returns elements, so you can test it like any other function.
It is not always the right pick. If a designer hands you HTML files to fill in, a template engine fits better. If the output is three lines, an f-string is quicker than any library.
Which way to generate HTML with Python
- A few lines, values you control: f-string plus
html.escape. - A fixed template with slots, perhaps edited by non-programmers:
string.Template. - Many pages written as HTML files, or a framework that expects them: Jinja2.
- HTML assembled from data and reusable parts, all in Python: an object library such as Nitro UI.
Common questions
Is there a built-in Python HTML generator? No. The standard library escapes and parses HTML but does not build it. You write strings or install a library.
Do I always need html.escape? For any value you did not write yourself, yes. Usernames, form input, file contents and database rows can all contain < or &.
How do I save the HTML to a file? It is a string, so write it like any text: Path("page.html").write_text(output, encoding="utf-8").
Can Python run inside an HTML page like JavaScript? Not natively. Python normally generates the HTML on the server or at build time. Projects such as PyScript run Python in the browser, which is a separate topic.
This page uses Nitro UI.
Create HTML with Python classes instead of strings. Type-safe, autocomplete-friendly, zero dependencies.
$ pip install nitro-ui