Last active
July 29, 2022 19:29
-
-
Save abitrolly/a48a6156db9296a851653493961da9e8 to your computer and use it in GitHub Desktop.
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
# public domain code | |
# useful for csv output etc. | |
def format_table(rows, headers): | |
"""Format list of tuples into equal width table with headers""" | |
maxlens = [len(h) for h in headers] | |
for r in rows: | |
for i, c in enumerate(r): | |
maxlens[i] = max(maxlens[i], len(c)) | |
tpltpl = [] | |
for i, m in enumerate(maxlens): | |
tpltpl.append('{%s:<%s}' % (i, m)) | |
# {0:12} {1:7} {2:10} {3:8} | |
templ = ' '.join(tpltpl) + '\n' | |
out = templ.format(*headers) | |
out += templ.format(*['-'*m for m in maxlens]) | |
for r in rows: | |
out += templ.format(*r) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment