How to programmatically generate markdown output in Jupyter notebooks?

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'))

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


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.