Created
July 17, 2011 04:26
-
-
Save thepaul/1087177 to your computer and use it in GitHub Desktop.
print stuff arranged in a table with silly ascii box characters
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 center(text, width): | |
if len(text) < width: | |
diff = width - len(text) | |
pad = ' ' * (diff / 2) | |
text = pad + text + pad | |
if diff % 2: | |
text += ' ' | |
return text | |
def print_table(fieldnames, table, outstream=None): | |
""" | |
Print a table of data to the given file-like stream (by default, stdout), | |
drawing lines between the columns and headers with crude ASCII box | |
characters (+, -, |). | |
The fieldnames argument should be a list of strings, corresponding to the | |
names of the columns in the table. | |
The table argument should be represented as a list of rows. Rows should be | |
lists of values, and should each have the same length as fieldnames. | |
All row values and field names should be bytes (i.e., str, not unicode). | |
>>> table = [ | |
... ['monkey', 'banana', 'tree frog'], | |
... ['giraffe', 'acacia', 'lemur'], | |
... ['wombat', 'grass', 'mouse'] | |
... ] | |
>>> headers = ['animal', 'favorite food', 'nemesis'] | |
>>> print_table(headers, table) | |
animal | favorite food | nemesis | |
---------+---------------+----------- | |
monkey | banana | tree frog | |
giraffe | acacia | lemur | |
wombat | grass | mouse | |
""" | |
if outstream is None: | |
outstream = sys.stdout | |
col_widths = [len(f) for f in fieldnames] | |
for row in table: | |
for colnum, value in enumerate(row): | |
col_widths[colnum] = max(col_widths[colnum], len(value)) | |
outstream.write(' ' + ' | '.join([center(f, w) for (w, f) in zip(col_widths, fieldnames)]) + ' \n') | |
outstream.write('+'.join(['-' * (w + 2) for w in col_widths]) + '\n') | |
for row in table: | |
outstream.write('|'.join([' %-*s ' % (w, v) for (w, v) in zip(col_widths, row)]) + '\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment