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.
Asked
Active
Viewed 3,976 times
1
-
Oh, fantastic! That makes a lot of sense. Thank you. – Daniel Sep 27 '16 at 17:51
-
@ZdaR: "*printed output to be of 4 characters at max*". I think you meant at **minimum**. If more than 4 characters are presented then they will be in the final string, if less then they will be padded. The number is a minimum field width, just like in `printf "%4s"`. Try `"{:4}".format("123456")`. As the doc says: "*width is a decimal integer defining the minimum field width.*" https://docs.python.org/3/library/string.html#formatspec – cdarke Sep 27 '16 at 17:59
1 Answers
3
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))

wpcarro
- 1,528
- 10
- 13