0

I'm trying to do one of the practice projects of How to automate the boring stuff. But I'm stuck.

Essentially, when given a list like:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

the program is supposed to print out the following table, where each column is right justified:

    apples Alice  dogs
   oranges   Bob  cats
  cherries Carol moose
    banana David goose

This is my code:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
                 ['Alice', 'Bob', 'Carol', 'David'],
                 ['dogs', 'cats', 'moose', 'goose']]
    
    def printTable():
        colWidths = [0] * len(tableData)
        for index in range(len(tableData)):
            colWidths[index] = len(max(tableData[index], key = len))
    
        for index in range(len(tableData)):
            for element in tableData[index]:
                print(element.rjust(colWidths[index]))
    
    printTable()
    

My problem is that each one of the lists gets properly right justified, but everything is printed out in a single column, not a table, like this:

  apples
 oranges
cherries
  banana
Alice
  Bob
Carol
David
 dogs
 cats
moose
goose

Is there any way I can add a new column after each iteration of the for loop? Or how would you improve my code?

Thank you for your help!

Juan11
  • 1

1 Answers1

1

print() has a parameter called end which has a newline assigned by default. This is creating the line breaks. To avoid the line breaks, use end="" as a parameter.

Still, that won't fix your issue, since your code is designed to output a column at a time. That's not how terminals work. Rewrite the code to output one line at a time.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222