Python Markdown

Converting with the markdown package, extensions, and sanitising the output.

Beginner
Key PointsMarkdown output is raw HTML — if the source is user-supplied you must sanitise it before rendering.

Basic Conversion

The markdown package converts text to an HTML fragment. Tables, highlighting and TOC need explicit extensions.

Bash
pip install markdown
Python
import markdown

text = """
# 标题

**粗体** 和 `code`

| 语言 | 课数 |
|---|---|
| Python | 60 |
"""
html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"])
print(html)
Output
<h1 id="_1">标题</h1>
<p><strong>粗体</strong> 和 <code>code</code></p>
<table>
<thead>
<tr><th>语言</th><th>课数</th></tr>
</thead>
<tbody>
<tr><td>Python</td><td>60</td></tr>
</tbody>
</table>

Useful Extensions

ExtensionAdds
tablesPipe tables
fenced_code``` code blocks
codehiliteSyntax highlighting classes
tocHeading ids and a TOC
nl2brNewline becomes <br>

Sanitising

Markdown allows raw HTML, so users can inject <script>. Sanitise before rendering — bleach is the usual choice.

Python
import bleach
import markdown

raw = markdown.markdown("<script>alert(1)</script>**hi**")
safe = bleach.clean(raw, tags=["p", "strong", "em", "code", "pre", "table", "tr", "td", "th"])
print(safe)
Output
<p>&lt;script&gt;alert(1)&lt;/script&gt;<strong>hi</strong></p>
Use raw markdown only for trusted content. Any user input must pass through bleach.clean().

Friends & Partners