1

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.

El-Chief
  • 383
  • 3
  • 15
  • 1
    This should point you in the right direction: https://stackoverflow.com/questions/20309255/how-to-pad-a-string-to-a-fixed-length-with-spaces-in-python –  Sep 13 '17 at 15:32
  • It most definitely did. Thanks – El-Chief Sep 13 '17 at 15:37

2 Answers2

3

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))
ettanany
  • 19,038
  • 9
  • 47
  • 63
1

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
Andy K
  • 4,944
  • 10
  • 53
  • 82