How to format into columns from a list using a function?

123 Views Asked by At

At the moment I have a list that is being found from a text document and is being searched with a for loop:

for sublist in mylist:
     if sublist[2] == inp:
         print (formatting(sublist)) 

This finds everything from the main list (mylist) and creates a sublist of of the wanted values. I then want to run this through a function to get it into the correct format.

function:

def formatting(sublist):

new_lis = []
widths = [max(map(len, col)) for col in zip(*sublist)]

for row in sublist:
    sub = ("  ".join((val.ljust(width) for val, width in zip(row, widths))))
    print(sub)
    new_lis.append(sub)
return new_lis

the input from the sub list to the def is :

['Bart Simpson', '12345', 'G400', '2']

after being ran through the function is looks like this:

['B', '1', 'G', '2'] 

when it should look like this:

[Bart Simpson,                  12345,  G400,   2]

I have no idea why it is doing it. I can only imagine that is taking the value from the first of each entity in the list and appending it. instead of appending the whole word.

1

There are 1 best solutions below

0
AudioBubble On

If you have a finite number of items in the sublist, you can use % formatting like so:

print('[%s, %22s, %5s, %3s]' % tuple(sublist))

The number before 's' is the width of the column in characters, and the string you wish to print is space-padded to that width.

NOTE: You must convert a list to tuple for this to work.