0

I have written a python code to print names and ages in different columns. The names and ages are stored in separate lists. The issue is, data gets aligned improperly while printing. I want data to be aligned properly in every column.Please suggest how do i modify the code to get proper output.

name=['pav sunny','sham sunny','mala','shalu']
age=[25,56,52,50]
print('''NAME\t\tAGE\n''')
for i in range(len(name)):
      print(name[i],'\t\t',age[i])
pavan sunder
  • 99
  • 4
  • 15
  • 3
    Possible duplicate of [How do I align text output in python?](http://stackoverflow.com/questions/17091446/how-do-i-align-text-output-in-python) – Picard May 18 '17 at 12:09

1 Answers1

0

well, you get the longest name with max(), then the length of the longest name, then you do some .ljust() and .rjust() and that's it, example:

name=['pav sunny','sham sunny','mala','shalu']
longest_name = max(name, key=len)
max_lenght = len(longest_name)
age=[25,56,52,50]
print('NAME'.ljust(max_lenght, ' '), '\t\t', 'AGE')
for i in range(len(name)):
      print(name[i].ljust(max_lenght, ' '), '\t\t', str(age[i]).rjust(3,' '))

this will output:

NAME             AGE
pav sunny         25
sham sunny        56
mala              52
shalu             50
Edwin van Mierlo
  • 2,398
  • 1
  • 10
  • 19