How to align numbers on the left using str.format?

Asked

Viewed 63 times

1

I’m studying about format strings and I’m not getting the same alignment behavior on the left with the minus sign (-) using the function format. What is the right way to do this using format?

>>> for x in range(1, 11):
...     print('%-2d %-3d %-4d %-6d' % (x, x**2, x**3, x**4))
... 
1  1   1    1     
2  4   8    16    
3  9   27   81    
4  16  64   256   
5  25  125  625   
6  36  216  1296  
7  49  343  2401  
8  64  512  4096  
9  81  729  6561  
10 100 1000 10000 
>>> for x in range(1, 11):
...     print('{0:-2d} {1:-3d} {2:-4d} {3:-6d}'.format(x, x**2, x**3, x**4))
... 
 1   1    1      1
 2   4    8     16
 3   9   27     81
 4  16   64    256
 5  25  125    625
 6  36  216   1296
 7  49  343   2401
 8  64  512   4096
 9  81  729   6561
10 100 1000  10000
  • I will leave the https://pyformat.info/ link if anyone wants a more simplified "documentation".

1 answer

4

In the method format, you must use < to align to the left:

for x in range(1, 11):
    print('{0:<2d} {1:<3d} {2:<4d} {3:<6d}'.format(x, x**2, x**3, x**4))

Exit:

1  1   1    1     
2  4   8    16    
3  9   27   81    
4  16  64   256   
5  25  125  625   
6  36  216  1296  
7  49  343  2401  
8  64  512  4096  
9  81  729  6561  
10 100 1000 10000 

More details about the formats can be seen on documentation.

Moreover, the same documentation indicates that the - is used to indicate that the signal should only be shown if the number is negative (and since all the numbers in your code are positive, this does not affect the output at all, and it uses the standard alignment, which for numbers is on the right).

This is different from the operator %, that according to the documentation uses the hyphen to align left.


From Python 3.6 you can use f-string, who also uses the < to align to the left:

for x in range(1, 11):
    print(f'{x:<2d} {x ** 2:<3d} {x ** 3:<4d} {x ** 4:<6d}')
  • Thank you very much for the reply and the documentation sources!!!!

  • @Gustavoabreu If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.