Search code examples
pythonstringpython-3.xstring-formatting

How can I add a new row which shows the number of columns into my code


I have lists as shown below:

l1=['N  N  N  N  M  M  M  W  W  N  W  W','N  W  W  W  N  N  N  N  N  N  N  N']
l2=['A','B','C','D','E','F']

And here is my code:

for i in range(len(l1)):
    print(l2[i],l1[i])

My output is:

A N  N  N  N  M  M  M  W  W  N  W  W
B N  W  W  W  N  N  N  N  N  N  N  N

I want a output like that (without using 3rd party libraries):

A N  N  N  N  M  M  M  W  W  N  W  W
B N  W  W  W  N  N  N  N  N  N  N  N
  0  1  2  3  4  5  6  7  8  9 10 11

I've tried something like that but it didn't work:

l3=[j for j in l1[0] if j!=' ']
print("  ",end='')
for k in range(len(l3)):
    print("{}  ".format(k),end='')

and output is like that:

A N  N  N  N  M  M  M  W  W  N  W  W
B N  W  W  W  N  N  N  N  N  N  N  N
  0  1  2  3  4  5  6  7  8  9  10  11 

Solution

  • With Python 3.6+, you can use formatted string literals (PEP489):

    l1 = ['N  N  N  N  M  M  M  W  W  N  W  W', 'N  W  W  W  N  N  N  N  N  N  N  N']
    l2 = ['A','B','C','D','E','F']
    
    for i, j in zip(l2, l1,):
        print(f'{i:>3}', end='')
        j_split = j.split()
        for val in j_split:
            print(f'{val:>3}', end='')
        print('\n', end='')
    
    print(f'{"":>3}', end='')
    for idx in range(len(j_split)):
        print(f'{idx:>3}', end='')
    

    Result:

      A  N  N  N  N  M  M  M  W  W  N  W  W
      B  N  W  W  W  N  N  N  N  N  N  N  N
         0  1  2  3  4  5  6  7  8  9 10 11