Skip to content
Python project #22Advanced

Markdown to HTML Converter

Convert Markdown headings, emphasis, code, links, lists, blockquotes, fenced code blocks and rules into clean, safely escaped HTML.

Estimated time
~5 hours to build
Files
4 files · 266 lines
Technologies
Python 3, re, html

Introduction

Every blog engine, documentation site and chat app converts Markdown into HTML. This converter handles the most-used features with a line-by-line block parser and regular expressions for inline formatting, and escapes HTML so user text can't inject tags.

Problem statement

Read Markdown from standard input and print HTML. Support headings # to ######, paragraphs joined from consecutive lines, bold, *italic*, code spans, [text](url) links, unordered lists (- or *), ordered lists (1.), multi-line > blockquotes, fenced ``` code blocks with an optional language class and horizontal rules (---). Escape <, > and & everywhere, and don't treat '2 * 3 * 4' as italic.

Objectives

  • Write a block-level parser with state
  • Apply inline rules with regular expressions in the right order
  • Escape HTML safely
  • Handle edge cases such as stray asterisks

Features

  • Headings, paragraphs and horizontal rules
  • Bold, italic, inline code and links
  • Ordered and unordered lists
  • Blockquotes and fenced code blocks with language
  • HTML escaping everywhere

Concepts demonstrated

  • Parsing
  • Regular expressions with lookarounds
  • Escaping and security
  • State machines

System architecture

convert walks the lines, keeping the current paragraph and list type as state; helper closures flush paragraphs and close lists when a different block starts. Fenced code is copied verbatim (escaped) until the closing fence. inline splits out backtick code spans first, escapes the remaining text and then applies the bold, italic and link patterns; the italic pattern uses lookarounds so spaced asterisks aren't treated as emphasis.

Folder structure

TextProject tree
markdown-to-html/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

110 lines
Pythonmain.py
"""Markdown to HTML converter (a practical subset of Markdown).
Supported: headings (#..######), paragraphs, **bold**, *italic*, `code`, [links](url),
unordered (- or *) and ordered (1.) lists, > blockquotes, fenced ``` code blocks with an
optional language, horizontal rules (---) and HTML escaping.
Usage: python main.py < notes.md > notes.html
"""
import html
import re
import sys
INLINE = [
(re.compile(r"\*\*(.+?)\*\*"), r"<strong>\1</strong>"),
(re.compile(r"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])"), r"<em>\1</em>"),
(re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)"), r'<a href="\2">\1</a>'),
]
def inline(text: str) -> str:
"""Escape HTML, protect `code` spans, then apply bold, italic and links."""
parts = re.split(r"(`[^`]+`)", text)
out = []
for part in parts:
if part.startswith("`") and part.endswith("`") and len(part) > 1:
out.append(f"<code>{html.escape(part[1:-1])}</code>")
continue
escaped = html.escape(part, quote=False)
for pattern, replacement in INLINE:
escaped = pattern.sub(replacement, escaped)
out.append(escaped)
return "".join(out)
def convert(markdown: str) -> str:
lines = markdown.splitlines()
out: list[str] = []
paragraph: list[str] = []
list_type: str | None = None
i = 0
def flush_paragraph() -> None:
if paragraph:
out.append(f"<p>{inline(' '.join(paragraph))}</p>")
paragraph.clear()
def close_list() -> None:
nonlocal list_type
if list_type:
out.append(f"</{list_type}>")
list_type = None
while i < len(lines):
line = lines[i]
stripped = line.strip()
if stripped.startswith("```"):
flush_paragraph()
close_list()
language = stripped[3:].strip()
body = []
i += 1
while i < len(lines) and not lines[i].strip().startswith("```"):
body.append(html.escape(lines[i]))
i += 1
attr = f' class="language-{language}"' if language else ""
out.append(f"<pre><code{attr}>" + "\n".join(body) + "</code></pre>")
elif not stripped:
flush_paragraph()
close_list()
elif m := re.match(r"(#{1,6})\s+(.*)", stripped):
flush_paragraph()
close_list()
level = len(m[1])
out.append(f"<h{level}>{inline(m[2].rstrip('#').strip())}</h{level}>")
elif re.fullmatch(r"(-{3,}|\*{3,})", stripped):
flush_paragraph()
close_list()
out.append("<hr>")
elif m := re.match(r"([-*]|\d+\.)\s+(.*)", stripped):
flush_paragraph()
wanted = "ol" if m[1][0].isdigit() else "ul"
if list_type != wanted:
close_list()
out.append(f"<{wanted}>")
list_type = wanted
out.append(f" <li>{inline(m[2])}</li>")
elif stripped.startswith(">"):
flush_paragraph()
close_list()
quote = []
while i < len(lines) and lines[i].strip().startswith(">"):
quote.append(lines[i].strip()[1:].strip())
i += 1
out.append(f"<blockquote><p>{inline(' '.join(quote))}</p></blockquote>")
continue
else:
close_list()
paragraph.append(stripped)
i += 1
flush_paragraph()
close_list()
return "\n".join(out)
def main() -> None:
print(convert(sys.stdin.read()))
if __name__ == "__main__":
main()

What each file does

main.py
The block parser, the inline formatter and the command-line entry point.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
<h1>Learning Python</h1>
<p>Python is <strong>easy to read</strong> and <em>fun to write</em>. It runs almost everywhere.</p>
<h2>Why learn it?</h2>
<ul>
<li>Huge standard library</li>
<li>Great for <code>data</code> and <em>automation</em></li>
<li>Friendly community: <a href="https://www.python.org">python.org</a></li>
</ul>
<h3>Getting started</h3>
<ol>
<li>Install Python</li>
<li>Open a terminal</li>
<li>Run <code>python --version</code></li>
</ol>
<blockquote><p>Simple is better than complex. Readability counts.</p></blockquote>
<pre><code class="language-python">def greet(name):
return f&quot;Hello, {name} &lt;3&quot;</code></pre>
<p>Special characters like &lt;tags&gt; &amp; ampersands are escaped. 2 * 3 * 4 is not italic.</p>
<hr>
<p>Thanks for reading!</p>
Input
# Learning Python

Python is **easy to read** and *fun to write*.
It runs almost everywhere.

## Why learn it?

- Huge standard library
- Great for `data` and *automation*
- Friendly community: [python.org](https://www.python.org)

### Getting started

1. Install Python
2. Open a terminal
3. Run `python --version`

> Simple is better than complex.
> Readability counts.

```python
def greet(name):
    return f"Hello, {name} <3"
```

Special characters like <tags> & ampersands are escaped. 2 * 3 * 4 is not italic.

---

Thanks for reading!

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Two lines of the first paragraph are joined into one <p>.
  • The code block keeps its indentation, gets class="language-python" and has its quotes and < escaped.
  • '<tags> & ampersands' are escaped and '2 * 3 * 4' stays plain text.

Common errors

Text inside `code` gets bold or italic

Split out code spans before applying the inline patterns.

User input can inject <script> tags

Escape text with html.escape before adding any markup.

Possible improvements

  • Support nested lists
  • Add tables
  • Wrap the output in a full HTML document with a stylesheet

Additional challenges

  1. 1Generate a table of contents with anchor links from the headings.
  2. 2Support images: ![alt](src).
  3. 3Write unit tests for every Markdown feature.

Built and tested it yourself? Mark it to update your dashboard.