El-Chief
El-Chief

Reputation: 384

Printing lists in columns from a text file

I made a small program where a user enters a name and a present they would give to someone. This data is then saved in the format ["name","present"] and then a new line for new inputs in a text file.

When I print it, it appears like this.

["bob","car"]
["charlie","mansion"]

Which is to be expected. I want to print it in columns so it prints like this.

bob        car
charlie    mansion

I know how to remove [],' so it displays properly but don't know how to print in columns.

I did research and found methods like zip but they print the text like this.

bob     charlie
car     mansion

Which isn't the order I want it in.

Upvotes: 1

Views: 234

Answers (2)

Andy K
Andy K

Reputation: 5044

There can be more pythonic ways but here's my solution

In [58]: a = ["bob","car"]

In [59]: b = ["charlie","mansion"]

In [60]: cc = [a,b]

In [61]: for item in cc:
 ...:         print("{:<7} {:<7}".format(item[0],''.join(map(str,item[1:]))))

bob     car
charlie mansion

Upvotes: 1

ettanany
ettanany

Reputation: 19806

You will need to determine the longest name in your data to use its lenght to format your data:

data = [
    ["bob", "car"],
    ["charlie", "mansion"]
]

n = max(len(item[0]) for item in data) + 5  # We add 5 more spaces between columns

for item in data:
    print('{:<{n}} {}'.format(*item, n=n))

Upvotes: 3

Related Questions