Skip to content

Instantly share code, notes, and snippets.

@m0neysha
Last active May 3, 2024 15:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save m0neysha/219bad4b02d2008e0154 to your computer and use it in GitHub Desktop.
Save m0neysha/219bad4b02d2008e0154 to your computer and use it in GitHub Desktop.
Python lists to markdown table
def make_markdown_table(array):
""" Input: Python list with rows of table as lists
First element as header.
Output: String to put into a .md file
Ex Input:
[["Name", "Age", "Height"],
["Jake", 20, 5'10],
["Mary", 21, 5'7]]
"""
markdown = "\n" + str("| ")
for e in array[0]:
to_add = " " + str(e) + str(" |")
markdown += to_add
markdown += "\n"
markdown += '|'
for i in range(len(array[0])):
markdown += str("-------------- | ")
markdown += "\n"
for entry in array[1:]:
markdown += str("| ")
for e in entry:
to_add = str(e) + str(" | ")
markdown += to_add
markdown += "\n"
return markdown + "\n"
@dfendr
Copy link

dfendr commented Apr 13, 2022

Thanks for putting this out, saved me time and helped me automate a report for my job.

@TimMcCauley
Copy link

TimMcCauley commented Jun 15, 2022

A more pythonic way making heavy use of f-strings would be something like

def make_markdown_table(array):
    """ the same input as above """

    nl = "\n"

    markdown = nl
    markdown += f"| {' | '.join(array[0])} |"

    markdown += nl
    markdown += f"| {' | '.join(['---']*len(array[0]))} |"

    markdown += nl
    for entry in array[1:]:
        markdown += f"| {' | '.join(entry)} |{nl}"

    return markdown

@OsKaR31415
Copy link

My take on it : https://gist.github.com/OsKaR31415/955b166f4a286ed427f667cb21d57bfd

It makes the table more readable (centers everything, aligns the columns), and it allows you to choose the markdown centering (the :--- syntax.

I also tried to make it as robust as possible to edge cases.

@neilwang0913
Copy link

Having some implementation examples to use the above source code will be great. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment