Search code examples
markdowninlinedisplayquarto

How can I use display Markdown in a qmd file?


I am aksing myself how I can use display Markdown in a qmd file corretly. I have this code:

```{python}
#| echo: true

# Pandas laden
import pandas as pd 

# csv Datei über read_csv laden
file = "Priorisierung_der_Anforderungen.csv"
df = pd.read_csv(file)
Anzahl_Karten = str(len(df))

from IPython.display import display, Markdown

display(Markdown("""
# Lesen der Daten

Im Anforderungsworkshop wurden insgesamt {Anzahl_Karten} Anforderungskarten der Teilnehmenden in einer Excel Tabelle erfasst.
""")).format(Anzahl_Karten)

```

I want to include the variable 'Anzhal_Karten' in the text. I understand that I need to use display, Markdown for this.

But I receive thids error:

AttributeError: 'NoneType' object has no attribute 'format'

And my output looks like this:

Lesen der Daten
Im Anforderungsworkshop wurden insgesamt {Anzahl_Karten} Anforderungskarten der Teilnehmenden in einer Excel Tabelle erfasst.

Thank you for any tips. Sebastian


Solution

  • You are receiving the error AttributeError: 'NoneType' object has no attribute 'format' becuase you are using the string format method on display. And display returns None if no display_id is given (default). But NoneType has no format method or attribute. Hence the error.

    So you need to format the string inside the Markdown function. And I would suggest using f-string (introduced in python 3.6, read the PEP 498)

    ---
    title: Display Markdown
    format: html
    jupyter: python3
    ---
    
    ```{python}
    #| echo: true
    
    # Pandas laden
    import pandas as pd 
    
    # csv Datei über read_csv laden
    file = "Priorisierung_der_Anforderungen.csv"
    df = pd.read_csv(file)
    Anzahl_Karten = str(len(df))
    
    from IPython.display import display, Markdown
    
    display(Markdown(f"""
    # Lesen der Daten
    
    Im Anforderungsworkshop wurden insgesamt {Anzahl_Karten} Anforderungskarten der Teilnehmenden in einer Excel Tabelle erfasst.
    """))
    
    ```
    

    f-string in Markdown