bob bob - 21 days ago 6
Python Question

How do I convert this output to a table

This is my output and my attempt at printing a formatted table, however it keeps giving the error "zero length field name in format".
How can I print the output as a formatted table without using modules and preferably this/similar method:

The names are made up for testing purposes:)

code:

newOrder = ['gtin','name','price','quantity'],['01234567', 'apples', '1.50', '12',],['01234566', 'applesxyz', '1.50', '12',],['01234565', 'asdasdapples', '1.50', '102',],['11234567', 'apples', '1.50', '12',]


formatting = [8,0,0,0]

for i in range(1,4):

maxLength = 0

for j in range(len(newOrder)):

if len(newOrder[j][i])>maxLength:

maxLength = len(newOrder[j][i])

formatting[i] = maxLength

lineFormatting = "{:<"+str(maxLength)+"} {:<10} {:<10} {:<10}"

print lineFormatting

print

for a,b,c,d in (newOrder[0], newOrder[1], newOrder[2], newOrder[3]):

print(lineFormatting.format(a,b,c,d))

Answer
newOrder = [['gtin', 'name', 'price', 'quantity'], ['01234567', 'apples', '1.50', '12', ],
            ['01234566', 'applesxyz', '1.50', '12', ], ['01234565', 'asdasdapples', '1.50', '102', ],
            ['11234567', 'apples', '1.50', '12', ]]

widths = [max(len(row[i]) for row in newOrder) for i in range(len(newOrder[0]))]

for row in newOrder:
    print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))

Output:

gtin     | name         | price | quantity
01234567 | apples       | 1.50  | 12      
01234566 | applesxyz    | 1.50  | 12      
01234565 | asdasdapples | 1.50  | 102     
11234567 | apples       | 1.50  | 12  

This was based on my answer here. I didn't want to mark it as a duplicate since this question doesn't involve CSVs.