简体   繁体   中英

Python - Markdown Table - Only showing first row in Streamlit

I can try and produce a reproducible example if need be, but thought I would show the code first. I am using Streamlit and a function which takes a JSON file and produces a table from it in markdown:

      table = f"""
      |Rank|Title|Value|{"# words|" * n_words}{"Similarity|" * distance}
      |--|--|--|--|--|
      """
        for i, el in enumerate(data):
            line = f"""|{i + 1}|**{el["title"]}**|£{el["value"]:,}|"""
            if n_words:
                line += f"""{str(el["n_words"])}|"""
            if distance:
                line += f"""{str(round(el["distance"], 2))}"""
            line = f"""{line}
                """
            table += line
    
        st.markdown(table)

For some reason, it is working for the first row, but not for any other rows. Am I doing anything which is obviously wrong?

在此处输入图像描述

Many thanks!

You have two issues.

  1. The call to markdown needs to be outdented so that it is called after the for loop ends, instead of at the end of the first cycle.
  2. You need to remove the indentation from your string literal.

Specifically, this line...

line = f"""{line}
                """

... causes every line after the first one to be indented by 16 spaces. Of course, Markdown sees that indentation as an indication that the indented text is a code block.

The simple fix would be to replace that line with:

line = f"{line}\n"

If you really wanted the string literal, then you might want to consider making use of thetextwrap.dedent function.

Although, I would make table a list and then append each line. After all of the lines are appended, then join the lines. In fact, you could do the same for all the cells as well. Like this:

table = [
    f"|Rank|Title|Value|{"# words|" * n_words}{"Similarity|" * distance}",
    "|--|--|--|--|--|"
]
for i, el in enumerate(data):
    line = [f"{i + 1}", f'**{el["title"]}**', f'£{el["value"]:,}']
    if n_words:
        line.append(f'{str(el["n_words"])}')
    if distance:
        line.append(f'{str(round(el["distance"], 2))}')
    table.append(f'|{"|".join(line)}|')
st.markdown("\n".join(table))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM