187 words
1 minute
Syntax highlighting Python console examples with GFM
Anubhav Gain
2024-02-02

Syntax highlighting Python console examples with GFM#

It turns out GitHub Flavored Markdown can apply syntax highlighting to Python console examples, like this one:

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

The trick is to use the following:

```pycon
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
```

I figured out the pycon code by scanning through the languages.yml file for linguist, the library GitHub use for their syntax highlighting.

While writing this TIL I also learned how to embed triple-backticks in a code block - you surround the block with more-than-three backticks (thanks to this tip):

````
```pycon
>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
```
````
Syntax highlighting Python console examples with GFM
https://mranv.pages.dev/posts/syntax-highlighting-python-console-examples-with-gfm/
Author
Anubhav Gain
Published at
2024-02-02
License
CC BY-NC-SA 4.0