Can I print the value of a variable in Markdown Cell Jupyter Notebook?
Tried Code:
value = 5.3 Markdown cell --> Value is {{ value }}
I want that the Markdown cell should display the value of variable
SCREENSHOT
Surprisingly, Jupyter Notebooks do not support the inclusion of variables in Markdown Cells out of the box. If you still use Jupyter Notebooks there is a readily solution: the Python Markdown extension. It is part of the nbextensions package which is easy to install and configure.
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.
Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.
@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:
nbconvert
to ignore the tagged cells, e.g. by adding this c.TagRemovePreprocessor.remove_input_tags = {"hide"}
to your ~/.jupyter/jupyter_notebook_config.py
config fileI 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:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With