<p>@nilansh bansal的答案对Jupyter笔记本非常有用。不幸的是,它不适用于JupyterLab,因为该插件不再受支持(就像所有nbextension插件一样)。由于JupyterLab越来越受欢迎,我想补充到目前为止的答案,因为我花了相当长的时间来寻找解决方案。这是因为到目前为止还没有与JupyterLab兼容的插件。我通过组合<a href="https://stackoverflow.com/a/47310524/5251061">this</a>和<a href="https://stackoverflow.com/questions/53443437/removing-certain-cells-via-tags-fails-due-to-wrong-type">this</a>找到了下面的解决方案,所以答案是:</p>
<pre><code>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))
</code></pre>
<p>或者,最后一行可以简化为Python的<a href="https://stackoverflow.com/questions/52812231/print-variable-in-jupyter-notebook-markdown-cell-python#comment101048628_57023238">@Igor Fobia</a>>;3.6所建议的那样:</p>
<pre><code>md(f"The data consists of {n} observations. Bla, Bla, ....")
</code></pre>
<p>这将产生所需的输出。然而,它有一个巨大的缺点,即导出NB时代码单元仍然可见。这可以通过以下方式解决:</p>
<ol>
<li>在代码单元格中添加标记,即将其命名为“hide”</li>
<li>配置<code>nbconvert</code>忽略标记的单元格,例如,将此<code>c.TagRemovePreprocessor.remove_input_tags = {"hide"}</code>添加到<code>~/.jupyter/jupyter_notebook_config.py</code>配置文件中</li>
</ol>
<p>我已经写了一篇详细的<a href="https://data-dive.com/jupyterlab-markdown-cells-include-variables" rel="nofollow noreferrer">blog-post</a>文章,介绍了如何在我的博客上实现这个用于发布笔记本的解决方案。例如,您可以安装JupyterLab的<code>jupyterlab-celltags</code>插件来简化细胞标记。</p>