0

I want to programmatically generate a report using Jupyter and need to put variables inside of markdown tables. I found this related answer: Related Answer.

However, if you put the code inside a for loop, the table and list are not formatted as desired (tested in Google Colab, Pycharm and Jupyter Notebook).

from IPython.display import display_markdown

for i in range(2):
    display_markdown(f'''## heading
    - ordered
    - list

    The table below:

    | id |value|
    |----|-----|
    | a  | {i} |
    | b  |  2  |
    ''', raw=True)

Tested code in Jupyter Notebook, Pycharm and Google Colab. The code delivers properly formatted text if used outside of for loop.

Edit This question Link describes the underlying problem. However, I believe that the different context (markdown formatting) and the is helpful for future searches.

tosogoso
  • 1
  • 1
  • Your formatting of the string to be aligned with the indentation of the `for` loop causes there to be extra leading spaces in the string which messes up the markdown. You have to omit the indentation from the string. – mkrieger1 Apr 08 '23 at 19:15

1 Answers1

0

As mkrieger's comments get out, the problem is with the extra spacing you added at the start of lines:

This version hews very close to yours and yet works:

from IPython.display import display_markdown

for i in range(2):
    display_markdown(f'''## heading
- ordered
- list

The table below:

| id |value|
|----|-----|
| a  | {i} |
| b  |  2  |
''', raw=True)

I simply removed the extra spaces at the start of the lines after the first.


Here is a version of your code looping with a string replacement to accomplish the same thing:

s='''## heading
- ordered
- list

The table below:

| id |value|
|----|-----|
| a  | PLACEHOLDER_FOR_VALUE |
| b  |  2  |'''

# code based on https://discourse.jupyter.org/t/jupyterlab-dictionary-content-output-format/5863/2?u=fomightez
from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))
for i in range(2):
    printmd(s.replace("PLACEHOLDER_FOR_VALUE",f"{i}"))

I'm using the variation of making markdown from a string that I am familiar with, see here.


By the way. If you are looking to assemble reports using Jupyter, nbformat is something you may want to look into.

The intro at the top of here will probably help you see how nbformat might be helpful for what you. Importantly, the abstractions of the notebook & cells & types of cells is all baked in and you can easily output new notebooks with contents as you design programmatically.

See here and here for more examples with code.

Wayne
  • 6,607
  • 8
  • 36
  • 93