DEV Community

MrRobot
MrRobot

Posted on

Pygments – Syntax Highlighting for Code and Text in python

Pygments is a powerful Python library for syntax highlighting of code in various programming languages. It supports hundreds of languages and formats, making it ideal for documentation generators, static site builders, and any application that needs to display code beautifully. It can output highlighted code in HTML, LaTeX, RTF, SVG, and more formats.


Installation:

pip install Pygments
Enter fullscreen mode Exit fullscreen mode

Example usage:

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print("Hello, world!")'
html = highlight(code, PythonLexer(), HtmlFormatter(full=True))
with open("example.html", "w") as f:
    f.write(html)
Enter fullscreen mode Exit fullscreen mode

PyPI page: https://pypi.org/project/Pygments/
GitHub page: https://github.com/pygments/pygments


3 Project Ideas:

  1. Build a syntax-highlighted code viewer for a web app or blog.
  2. Create a Markdown-to-HTML converter that highlights code blocks.
  3. Develop a command-line tool to generate highlighted PDFs or HTML files from source code.

Top comments (0)