Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Created March 21, 2015 09:49
Show Gist options
  • Select an option

  • Save OzTamir/57a876872d2d5090b3b1 to your computer and use it in GitHub Desktop.

Select an option

Save OzTamir/57a876872d2d5090b3b1 to your computer and use it in GitHub Desktop.
Print formatted tables in Python (Rows might overflow, but otherwise the output is pretty
def show_table(titles, rows, table_name=None, sep_rows=False):
'''
Print a pretty, formatted and spaced table
Parameters:
- header (iterable) : Sequence with titles for each column
- rows (iterable) : Sequence of rows in the table,
must contain len(header) items.
- table_name (str): if the caller want to, print a title
- sep_rows (bool): should the function print a seperetor between values
'''
# If we have no data, create a NULL line
if len(rows) == 0:
rows.append(['NULL' for i in titles])
# Even if we don't have column titles, we still to know how many there are
if titles is None:
titles = ['' for x in rows[0]]
# Print a newline as a seperetor
print('')
# Lambda function to find the biggest string for each column
get_biggest = lambda x: max([max([str(row[x]) for row in rows], key=len),\
titles[x]], key=len)
# Find the biggest string in each column
biggest_strings = [len(get_biggest(i)) for i, x in enumerate(titles)]
# Print seperetor (the size of the biggest string + 3 for ' | ' seperetors)
print_seperetor(sum(biggest_strings) + (3 * (len(titles) + 1)))
# If we have a table name, print it
if table_name is not None:
# Add the number of items to the title
table_name = '%s (%d)' % (str(table_name), len(rows))
# Width of table - place for '|' at start at end of line
size = (sum(biggest_strings) + (3 * (len(titles) + 1))) - 4
print(' |%s|' % str(table_name).center(size, ' '))
# Print seperetor (the size of the biggest string + 3 for ' | ' seperetors)
print_seperetor(sum(biggest_strings) + (3 * (len(titles) + 1)))
# If the titles are real and weren't created in the above if
if not (filter(None, titles) == []):
# Craft header for the table
line = ['']
for idx, header in enumerate(titles):
# We use str.center to have nice formatting and spacing
line.append(str(header).center(biggest_strings[idx], ' '))
# Append empty string to have another ' | ' at the end of the line
line.append('')
# Print the header of the table
print(' | '.join(line))
# Print seperetor (the size of the biggest string + 3 for ' | ' seperetors)
print_seperetor(sum(biggest_strings) + (3 * (len(titles) + 1)))
# Print the rows
for row in rows:
line = ['']
# Craft a line
for idx, item in enumerate(row):
# We use str.center to have nice formatting and spacing
line.append(str(item).center(biggest_strings[idx]))
# Append empty string to have another ' | ' at the end of the line
line.append('')
# Print the line
print(' | '.join(line))
# If we should seperate values
if sep_rows:
# Print another seperetor
print_seperetor(sum(biggest_strings) + (3 * (len(titles) + 1)))
# If we are seperating values, there is already a seperator
if not sep_rows:
# Print seperetor (the size of the biggest string + 3 for ' | ' seperetors)
print_seperetor(sum(biggest_strings) + (3 * (len(titles) + 1)))
# Print a newline as another seperetor
print('')
def print_seperetor(size=10):
'''
Print a seperetor to sepreate different sections of the UI
Parameters:
- size (int): the size of the seperetor
'''
# Make sure it's an int
if not isinstance(size, int):
size = 10
print('-' * size)
@OzTamir
Copy link
Author

OzTamir commented Mar 21, 2015

Example:

from utils import show_table

table_name = 'Projects'
columns = ('Name', 'Description')
rows = (
    ('Databases-Project', 'End of term MySQL project'),
    ('TalkASM', 'Client-Server based chat written in x86 Assembly'),
    ('oZip', 'Simple text compression using Python and Huffman trees')
    )

show_table(columns, rows, table_name, True)

'''
Output:

--------------------------------------------------------------------------------
 |                                Projects (3)                                |
--------------------------------------------------------------------------------
 |        Name       |                      Description                       | 
--------------------------------------------------------------------------------
 | Databases-Project |               End of term MySQL project                | 
--------------------------------------------------------------------------------
 |      TalkASM      |    Client-Server based chat written in x86 Assembly    | 
--------------------------------------------------------------------------------
 |        oZip       | Simple text compression using Python and Huffman trees | 
--------------------------------------------------------------------------------

'''

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment