Skip to content

Instantly share code, notes, and snippets.

@abitrolly
Last active July 29, 2022 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abitrolly/a48a6156db9296a851653493961da9e8 to your computer and use it in GitHub Desktop.
Save abitrolly/a48a6156db9296a851653493961da9e8 to your computer and use it in GitHub Desktop.
# 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