Skip to content

Instantly share code, notes, and snippets.

@scientificRat
Created August 14, 2018 03:37
Show Gist options
  • Save scientificRat/092e90d347471567f8f1253a8102398d to your computer and use it in GitHub Desktop.
Save scientificRat/092e90d347471567f8f1253a8102398d to your computer and use it in GitHub Desktop.
print table to console
def print_table(head, body, padding_left=1, padding_right=2):
# calc column lens
head = list(head)
col_lens = [len(c) + padding_left + padding_right for c in head]
for i in range(len(body)):
body[i] = list(body[i])
row = body[i]
if len(row) > len(head):
head.append('')
col_lens.append(0)
for j in range(len(row)):
row[j] = str(row[j])
curr_len = len(row[j]) + padding_left + padding_right
if curr_len > col_lens[j]:
col_lens[j] = curr_len
# print
print_table_line(col_lens)
print('\n|', end='')
for i in range(len(head)):
print(padding_left * ' ' + '%-*s' % (col_lens[i] - padding_left, head[i]), end='|')
print()
print_table_line(col_lens)
for row in body:
print('\n|', end='')
for i in range(len(row)):
print(padding_left * ' ' + '%-*s' % (col_lens[i] - padding_left, row[i]), end='|')
# print_table_line(col_lens)
print()
print_table_line(col_lens)
print()
def print_table_line(col_lens):
print('+', end='')
for l in col_lens:
print('-' * l, end='+')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment