Daniel Daniel - 29 days ago 5
Python Question

What does {:4} mean in this matrix printing solution in python?

In the solution to the question proposed here printing a two dimensional array in python I'm not able to figure out what the {:4} part of the solution means exactly. I've tried this print statement and it seems to work very well, but for cases where I have very large matrices, I want to make sure I'm not adding or slicing valuable information.


It has to do with padding and alignment in output. It is similar to padding in the printf function found in c or awk, etc. It gives each printed element a width of n where n is {:n}.

''.join('{:3}'.format(x) for x in range(100))

Will output:

'  0  1  2  3  4  5 ... 95 96 97 98 99'

Notice the single space to the left of 99 versus the two spaces to the left of 0. In other words, each number has a width of 3 characters.

You can also accomplish a similar effect using a more traditional syntax.

''.join('%3s' % x for x in range(100))