Skip to content

Instantly share code, notes, and snippets.

@simonLeary42
Created October 17, 2023 22:22
Show Gist options
  • Save simonLeary42/377ce7c4034b527d28ddf1442f37daa0 to your computer and use it in GitHub Desktop.
Save simonLeary42/377ce7c4034b527d28ddf1442f37daa0 to your computer and use it in GitHub Desktop.
`tabulate` but worse
def fmt_table(table, disable_column_headers=False) -> str:
"""
I would use tabulate but I don't want nonstandard imports
"""
table_output = ""
# no row has more elements than the header row
assert(all(len(row) <= len(table[0]) for row in table))
column_widths = [ 0 ] * len(table[0])
for row in table:
for i,element in enumerate(row):
if len(str(element)) > column_widths[i]:
column_widths[i] = len(str(element))
column_widths = [ x + 3 for x in column_widths ] # room for whitespace on either side
if not disable_column_headers:
table_output += "\033[4m" # start underline
for i,column_header in enumerate(table[0]):
if i > 0:
table_output += '|'
table_output += str(column_header).center(column_widths[i]-1) # minus one for the '|'
table_output += "\033[0m" # end underline
table_output += '\n'
table.pop(0)
for row in table:
for i,value in enumerate(row):
table_output += str(value).ljust(column_widths[i])
table_output += '\n'
return(table_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment