Last active
October 7, 2016 15:14
-
-
Save tdsymonds/75689ed95e5c052ce0fde39797f97d4f to your computer and use it in GitHub Desktop.
A simple Python script that prints a table with nicely formatted columns
This file contains hidden or 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 printTable(table, first_row_is_header=True, spacing=4): | |
# caluclate the number of columns | |
cols = len(table[0]) | |
# calculate the max width for each column | |
max_list = [None]*cols | |
for i in xrange(cols): | |
max_list[i] = max([len(str(x[i])) if i<len(x) else 0 for x in table]) | |
# calc row length for lines | |
row_length = sum(max_list)+(cols*spacing) | |
# create a row line for the table | |
row_line = ' ' + '-'*row_length | |
# print line at top of table | |
print row_line | |
# loop through each row in the table | |
for index, row in enumerate(table): | |
if first_row_is_header and index is 1: | |
# row after header so | |
# print line | |
print row_line | |
# loop through each col and create row text | |
row_text = '|' | |
for i in xrange(cols): | |
row_text += str(row[i]) + ' '*((max_list[i]+spacing)-len(str(row[i]))) | |
# and print | |
print row_text + '|' | |
# print bottom row | |
print row_line | |
if __name__ == '__main__': | |
table = [ | |
['first name', 'last name', 'company name', 'house no', 'address 1', 'postcode',], | |
['Aleshia', 'Tomkiewicz', 'Alan D Rosenburg Cpa Pc', 14, 'Taylor St','CT2 7PP'], | |
['Evan', 'Zigomalas', 'Cap Gemini America', 5, 'Binney St', 'P11 2AX'], | |
['France', 'Andrade', 'Elliott, John W Esq', 8, 'Moor Place', 'H6 3BE'], | |
['Ulysses', 'Mcwalters', 'Mcmahan, Ben L', 505, 'Exeter Rd', 'DN36 5RP'], | |
['Tyisha', 'Veness', 'Champagne Room', 5396, 'Forth Street', 'B70 9DT'], | |
['Eric', 'Rampy', 'Thompson, Michael C Esq', 9472, 'Lind St', 'NN14 2GH'], | |
['Marg', 'Grasmick', 'Wrangle Hill Auto Auct & Slvg', 7457, 'Cowl St', 'O14 3TY'], | |
['Laquita', 'Hisaw', 'In Communications Inc', 20, 'Gloucester Pl', 'E29 7AD'], | |
['Lura', 'Manzella', 'Bizerba Usa Inc', 929, 'Augustine St', 'BS16 4LL'], | |
['Yuette', 'Klapec', 'Max Video', 45, 'Bradfield St', 'DE6 1QN'], | |
['Fernanda', 'Writer', '', 620, 'Northampton St','DA2 7PP'], | |
['Charlesetta', 'Erm', 'Cain, John M Esq', 5, 'Hygeia St', 'S40 4LY'], | |
['Corrinne', 'Jaret', 'Sound Vision Corp', 2150, 'Morley St','DG8 7DE'], | |
['Niesha', 'Bruch', 'Rowley/hansell Petetin', 24, 'Bolton St', 'EH52 5TL'], | |
['Rueben', 'Gastellum', '', 4, 'Forrest St','BS23 3HG'], | |
['Michell', 'Throssell', 'Weiss Spirt & Guyer', 89, 'Noon St','P25 6JQ'], | |
] | |
printTable(table=table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment