Markdown2
Markdown2 is a fast and complete Python implementation of Markdown, designed to closely match the behavior of the original Perl-implemented Markdown.pl. It offers a core Markdown parser and numerous extensions, known as 'extras,' for enhanced functionality like syntax highlighting, tables, and header IDs. The library is actively maintained with periodic releases and currently supports Python 3.9 and newer.
Warnings
- deprecated The 'code-color' extra (for Pygments-based syntax highlighting) is deprecated. Use the 'fenced-code-blocks' extra instead, which offers better and more modern syntax highlighting capabilities.
- gotcha Markdown2 directly outputs HTML, including any raw HTML present in the input Markdown. If processing untrusted user-generated content, ensure you sanitize the resulting HTML with a dedicated HTML sanitizer (e.g., 'Bleach') to prevent Cross-Site Scripting (XSS) vulnerabilities.
- gotcha Inconsistent or incorrect Markdown syntax can lead to unexpected rendering. Common pitfalls include missing blank lines between paragraphs or block-level elements, lack of space after heading hashes (`#`), or incorrect indentation for lists and code blocks.
Install
-
pip install markdown2 -
pip install markdown2[all]
Imports
- markdown
from markdown2 import markdown
- Markdown
from markdown2 import Markdown
Quickstart
import markdown2
markdown_text = """
# Hello, Markdown2!
This is a paragraph with *emphasis* and **strong emphasis**.
- List item 1
- List item 2
```python
print('Hello from a code block!')
```
Checkout the [Markdown2 GitHub page](https://github.com/trentm/python-markdown2).
"""
# Basic conversion
html = markdown2.markdown(markdown_text)
print("--- Basic Conversion ---")
print(html)
# Conversion with an extra (e.g., 'fenced-code-blocks' for syntax highlighting)
html_with_extras = markdown2.markdown(markdown_text, extras=["fenced-code-blocks", "footnotes"])
print("\n--- Conversion with Extras ---")
print(html_with_extras)
# Using the class-based API
markdowner = markdown2.Markdown(extras=["tables", "header-ids"])
html_from_class = markdowner.convert("| Header 1 | Header 2 |\n|----------|----------|\n| Cell 1 | Cell 2 |\n\n### My Section")
print("\n--- Class-based Conversion with Extras ---")
print(html_from_class)