1

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 
jpp
  • 159,742
  • 34
  • 281
  • 339
Stewie
  • 151
  • 5
  • For what I see, your only problem are the trailing spaces before the numbers when they have 2 digits, is it right? – Luan Naufal Dec 09 '18 at 23:32
  • 1
    https://stackoverflow.com/questions/8450472/how-to-format-print-output-or-string-into-fixed-width - Take a look into that when it comes to formatting. – Rozart Dec 09 '18 at 23:33
  • Yes, you're right. – Stewie Dec 09 '18 at 23:33
  • 1
    If this is the case, just decide the number of `spaces` your `print` will add, based on the number of characters your index `j` has, so adding 1 less space if your number has digits: `print(" " * (3 - len(j) ))` should do the trick – Luan Naufal Dec 09 '18 at 23:34

3 Answers3

2

I guess you want characters and digits are right aligned. Modify last string formatting

print('{}'.format(..))

into

print(' { :>n}'.format(..))

Where n in this case is 2.

Answer is based on the Python: Format output string, right alignment

Wiseosho
  • 41
  • 4
1

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
jpp
  • 159,742
  • 34
  • 281
  • 339
0

I solved the problem using string formatting:

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

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
  0  1  2  3  4  5  6  7  8  9 10 11
Stewie
  • 151
  • 5