Print Variable In Jupyter Notebook Markdown Cell Python
@nilansh bansal's answer works great for Jupyter Notebooks. Unfortunately, it doesn't work for JupyterLab because the plugin is no longer supported (as is the case for all nbextension plugins). Since JupyterLab gains popularity, I wanted to complement the answers so far because it took me quite some time to find a solution. This is because until now there is no plugin compatible with JupyterLab. I have found the following solution for myself by combining this and this SO answers:
from IPython.display import Markdown as md
# Instead of setting the cell to Markdown, create Markdown from withnin a code cell!
# We can just use python variable replacement syntax to make the text dynamic
n = 10
md("The data consists of {} observations. Bla, Bla, ....".format(n))
Alternatively, the last line can be simplified as suggested by @Igor Fobia for Python >3.6:
md(f"The data consists of {n} observations. Bla, Bla, ....")
This leads to the desired output. However, it has the huge disadvantage that the code cell will still be visible when exporting the NB. This can be solved though:
- Add a tag to the code cell, i.e. name it "hide"
- Configure
nbconvert
to ignore the tagged cells, e.g. by adding thisc.TagRemovePreprocessor.remove_input_tags = {"hide"}
to your~/.jupyter/jupyter_notebook_config.py
config file
I have written a detailed blog-post about how I implemented this solution for publishing Notebooks on my blog. If you use JupyterLab < 2.0
, you could install the jupyterlab-celltags
plugin for JupyterLab to simplify the cell tagging.
So After going through all the links I was able to resolve the problem by referring to nbextension jupyter notebook docs : https://github.com/ipython-contrib/jupyter_contrib_nbextensions
Steps Taken:
- pip install jupyter_contrib_nbextensions
- jupyter contrib nbextension install --user
- jupyter nbextension enable python-markdown/main
After the above commands started a jupyter notebook and to print the value of a variable in the markdown cells works like charm!
You just have to use {{ ac_score }} within a markdown cell.
Screenshot
Thanks!