Reputation: 85
I have a short questions regarding the solution of Chapter 6 Practice Project in "Automate Boring Stuff with Python" book. I should write a function that take data in teh form of list of lists:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
and prints the following table with each column right-justified:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
The problem is, that my code:
def printTable(table):
colsWidths = [0]*len(table) #this variable will be used to store width of each column
# I am using max function with key=len on each list in the table to find the longest string --> it's length be the length of the colum
for i in range(len(table)):
colsWidths[i] = len(max(table[i], key = len)) # colsWidths = [8,5,5]
# Looping through the table to print columns
for i in range(len(table[0])):
for j in range(len(table)):
print(table[j][i].rjust(colsWidths[j], " "), end = " ")
print("\n")
prints the table with excessive empty lines between each row:
printTable(tableData)
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
I understand that it has something to do with the print statement that is written at the end of the program, but without it everything is printed. So my question is, is there a way to remove those empty rows from the table?
Upvotes: 1
Views: 681
Reputation: 2838
Replace print("\n")
with print()
print
by default prints a newline character, that's what the default value of end
parameter is.
When you do print("\n")
you are actually printing two new lines.
Upvotes: 2