Although i insert different string, str.format print same string

Viewed 51

I want to print different variable in one line with specific alignment. However, str.format print same string.

Here is the code what i did and output

>>> print("{0:^20} {0:^20} {0:^40}\n".format('chkitem', 'Count', 'Coordinate'))
      chkitem              chkitem                        chkitem       

     

I want to print

>>> print("{0:^20} {0:^20} {0:^40}\n".format('chkitem', 'Count', 'Coordinate'))
      chkitem              Count                        Coordinate       

What is the problem?

2 Answers
print("{:^20} {:^20} {:^40}\n".format('chkitem', 'Count', 'Coordinate'))

The zeroes before the colons are specifying to use the zero-indexed format argument, if you omit them it will default to use the next format argument provided.

You can also specify 0:, 1:, 2: and so on, but best practice is to only specify indexes if you want to print an argument more than once.

{0:^20} - 0 is position of item in format arguments. You have to increase it.

print("{0:^20} {1:^20} {2:^40}\n".format('chkitem', 'Count', 'Coordinate'))
Related