-2

So I have this code:

food={'banana': 3, 'fish': 10, 'pineapple': 1, 'apple': 7}

print("Food       "+"Amount")
for x in food:
    print (x,end="       ")
    print (food[x])

The output is this:

Food       Amount
banana       3
fish       10
pineapple       1
apple       7

But how can make the numbers line up like this:

Food       Amount
banana       3
fish         10
pineapple    1
apple        7

Any tips are appreciated.

  • `print(f"{x:>15} {food[x]:>10")` would be one option. Look at https://docs.python.org/3/library/string.html#formatspec for center, left/right alignment etc. – Patrick Artner Dec 16 '20 at 13:06
  • `print('\n'.join( f"{a:<10} {b:^5}" for a,b in ([("Food","Amount")] + [i for i in food.items()]) ))` – Patrick Artner Dec 16 '20 at 13:13

1 Answers1

0
food={'banana': 3, 'fish': 10, 'pineapple': 1, 'apple': 7}
print(f"{'Food':<12}Amount")
for key, val in food.items():
    print(f"{key:<12}  {val}")
big_bad_bison
  • 1,021
  • 1
  • 7
  • 12
  • may I ask what does `f"` do in the print statment? – redshorts17 Dec 16 '20 at 13:20
  • the `f` at the beginning turns it into an "f-string" allowing the use of Python expressions between `{` and `}` within the string. See https://docs.python.org/3/tutorial/inputoutput.html – big_bad_bison Dec 16 '20 at 13:36