I am following http://automatetheboringstuff.com/chapter6/
At the very bottom of the page is an exercise about formatting tables.
Here is my code:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidths = [0] * len(table)
for line in table:
max = 0
for word in line:
if len(word) > max:
max = len(word)
colWidths[table.index(line)] = max
for a in range(len(table)-2):
for b in range(len(table[0])):
print(table[a][b].rjust(colWidths[0])+table[a+1][b].rjust(colWidths[1])+table[a+2][b].rjust(colWidths[2]))
"""
print(table[0][0].rjust(colWidths[0]), table[1][0].rjust(colWidths[1]), table[2][0].rjust(colWidths[2]))
print(table[0][1].rjust(colWidths[0]), table[1][1].rjust(colWidths[1]), table[2][1].rjust(colWidths[2]))
print(table[0][2].rjust(colWidths[0]), table[1][2].rjust(colWidths[1]), table[2][2].rjust(colWidths[2]))
print(table[0][3].rjust(colWidths[0]), table[1][3].rjust(colWidths[1]), table[2][3].rjust(colWidths[2]))
"""
print()
printTable(tableData)
The commented out lines format everything how it should be. The actual code does not. For it to be formatted correctly, I would need to add 1 to .rjust()
for each column (eg with 100 columns I would have to .rjust(colWidths[1]+99)
).
Why does this happen when it seems to be working just fine when I just manually print?