Last active
August 15, 2024 18:36
-
-
Save m0neysha/219bad4b02d2008e0154 to your computer and use it in GitHub Desktop.
Python lists to markdown table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
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
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.
Having some implementation examples to use the above source code will be great. Thanks
def create_markdown_table(table):
if not table or not table[0]:
return "Empty table"
# Remove the first row if it's empty
if all(cell == "" or cell is None for cell in table[0]):
table = table[1:]
# Separate indentation from content in the first column
processed_table = []
for row in table:
first_cell = str(row[0])
indentation = len(first_cell) - len(first_cell.lstrip())
processed_row = [" " * indentation + first_cell.strip()] + list(row[1:])
processed_table.append(processed_row)
# Determine the maximum width of each column
col_widths = [
max(len(str(cell)) if cell is not None else 0 for cell in col)
for col in zip(*processed_table)
]
# Create the header
header = (
"| "
+ " | ".join(
str(cell).ljust(width)
for cell, width in zip(processed_table[0], col_widths)
)
+ " |"
)
# Create the separator
separator = "| " + " | ".join("-" * width for width in col_widths) + " |"
# Create the rows
rows = []
for row in processed_table[1:]:
row_str = (
"| "
+ " | ".join(
str(cell).ljust(width)
if i == 0
else str(cell).rjust(width)
if cell is not None
else " " * width
for i, (cell, width) in enumerate(zip(row, col_widths))
)
+ " |"
)
rows.append(row_str)
# Join all parts of the table
markdown_table = "\n".join([header, separator] + rows)
return markdown_table
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for putting this out, saved me time and helped me automate a report for my job.