173

I want to write a report for classes in Jupyter notebook. I'd like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I'd like such command: print '$\phi$' to generate phi symbol, just like in markdown.
In other words, I'd like to have a template made in markdown and insert the values generated by the program written in the notebook. Recalculating the notebook should generate new results and new markdown with those new values inserted. Is that possible with this software, or do I need to replace the values by myself?

8 Answers 8

285
+50

The functions you want are in the IPython.display module.

from IPython.display import display, Markdown, Latex
display(Markdown('*some markdown* $\phi$'))
# If you particularly want to display maths, this is more direct:
display(Latex('\phi'))
12
  • 2
    Thanks a lot, I guess this should help me significantly. If I may ask, is there a way to hide the cell with code? I mean, when I "compile" the markdown cell, the "code" disappears and only the compiled markdown output is visible. I'd like to be able to repeat this, but with display_markdown function.
    – fulaphex
    Mar 30, 2016 at 19:37
  • 2
    Unfortunately your code doesn't work for me, it doesn't produce any output.
    – fulaphex
    Mar 30, 2016 at 19:42
  • 2
    Now it does indeed work, thanks. Is there a command to hide a cell, so that I can generate this markdown and this would behave, like a normal markdown cell?
    – fulaphex
    Mar 30, 2016 at 20:08
  • 2
    The link in the previous comment doesn't work anymore, the extension can now be found at: github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/…
    – BioGeek
    May 11, 2017 at 10:07
  • 4
    I get the object not the print: <IPython.core.display.Markdown object> Apr 17, 2020 at 9:54
40

You are basically asking for two different things:

  1. Markdown cells outputting code results.

    I'd like to count some stuff, generate some results and include them in markdown. [...] I'd like to have a template in markdown and insert values generated by the program in the notebook

  2. Code cells outputting markdown

    I'd like such command: print '$\phi$' to generate phi symbol, just like in markdown.

Since 2. is already covered by another answer (basically: use Latex() or Markdown() imported from IPython.display), I will focus on the first one:


1. Markdown Template with inserted variables

With the Jupyter extension Python Markdown it actually is possible to do exactly what you describe.

Installation instructions can be found on the github page of nbextensions. Make sure you'll enable the python markdown extension using a jupyter command or the extension configurator.

With the extension, variables are accessed via {{var-name}}. An example for such a markdown template could look like this:

Python Code in Markdown Cells

The variable a is {{a}}

You can also embed LateX: {{b}} in here!

Even images can be embedded: {{i}}

Naturally all variables or images a, b, i should be set in previous code. And of course you may also make use of Markdown-Latex-style expressions (like $\phi$) without the print command. This image is from the wiki of the extension, demonstrating the capability.

example from wiki


Further info on this functionality being integrated into ipython/jupyter is discussed in the issue trackers for ipython and jupyter.

4
  • Is this available in Jupyter Lab?
    – BND
    Mar 23, 2019 at 15:04
  • I do not use that, hence have no experience. However I can't find "Python Markdown" in the jupyter-lab extension list: github.com/topics/jupyterlab-extension?q=&unscoped_q= - therefore: maybe no?
    – Honeybear
    Mar 24, 2019 at 17:04
  • Will this work e.g. with `nbconvert --to markdown``, or it works only in the web browser? Can't seem to make it work
    – Adam
    Sep 1, 2022 at 18:30
  • This extension does not work for Jupyter version >= 6.x
    – null
    Nov 14, 2023 at 13:49
11

As an addition to Thomas's answer. Another easier way to render markdown markup is to use display_markdown function from IPython.display module:

from IPython.display import display_markdown

display_markdown('''## heading
- ordered
- list

The table below:

| id |value|
|:---|----:|
| a  |  1  |
| b  |  2  |
''', raw=True)

Output below:

enter image description here

Usage example could be found on Google Colab Notebook

2
2

Another option is to use Rich for Markdown rendering and UnicodeIt for symbols. It has some limitations, as Rich uses CommonMark, which does not support tables, for example. Rich has other ways to render tables though; this is detailed in the documentation.

Here is an example:

from rich.markdown import Markdown
import unicodeit

alpha = unicodeit.replace('\\alpha')
epsilon = unicodeit.replace('\\epsilon')
phi = unicodeit.replace('\\phi')

MARKDOWN = f"""
# This is an h1

Rich can do a pretty *decent* job of rendering markdown.

1. This is a list item
2. This is another list item

## This is an h2

List of **symbols**:

- alpha: {alpha}
- epsilon: {epsilon}
- phi: {phi}

This is a `code` snippet:

```py
# Hello world
print('Hello world')
```

This is a blockquote:

> Rich uses [CommonMark](https://commonmark.org/) to parse Markdown.

---

### This is an h3

See [Rich](https://github.com/Textualize/rich) and [UnicodeIt](https://github.com/svenkreiss/unicodeit) for more information.
"""

Markdown(MARKDOWN)

... which produces the following output:

Rich + UnicodeIt output

0
from tabulate import tabulate
from IPython.display import Markdown
A2 = {
    'Variable':['Bundle Diameter','Shell Diameter','Shell Side Cross Flow area','Volumetric Flowrate','Shell Side Velocity'],
    'Result':[3.4, 34, 78.23, 1.0 ,  2.0],
    'Unit' : ['$in$', '$in$', '$ft^2$', '$ft^{3}s^{-1}$', '$fts^{-1}$']}
temp_html=tabulate(A2, headers='keys', tablefmt='html')
Markdown(temp_html.replace('<table>','<table style="width:50%">'))

.replace() usage will not break latex code & avoid column(s) overstrech. This way one can dynamically generate tables with Latex

0

One more option. There is an open-source framework for converting Jupyter notebooks to web apps. It is called Mercury. It has function called Markdown to display any string as Markdown. Here is a documentation.

Below is an example notebook that dynamically displays Markdown:

import mercury as mr
slider = mr.Slider(label="Favorite number", value=5)
name = "Piotr"
mr.Markdown(f"""# Hello {name}

## Your variable is {slider.value}
""")

notebook with markdown

Notebook and web app created with Mercury. It has dynamic Markdown: notebook and app with markdown

0

There is an interesting lab extension called jupyterlab-myst which will swap the standard markdown renderer in the notebook out for the mystjs renderer.

This means you can render more than standard commonmark markdown in markdown cells including being able to interpolate variable values directly into markdown. These can be simple variables, images, cell outputs and even ipywidgets.

This opens up a lot more possibilities on how you can interlace results from computation in code cells with markdown content in the notebooks. When a notebook is re-executed the interpolated values in the markdown will be updated.

There are other features that are helpful for report writing that could also help with the OP's use case.

Example of ipywidgets rendered in a markdown cell

0

I've created a simple ipython kernel where all code cells are just giving back Markdown. Should be perfect for teaching/showing Markdown syntax. You can check it out here.

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jul 26, 2023 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.