I am watching a video about the concept of Cross Validation. Here is a code snippet from that video:
from sklearn.cross_validation import KFold
kf = KFold(25, n_folds=5, shuffle=False)
print '{}{:^61}{}'.format('Iteration', 'Training set observations', 'Testing set observations')
for iteration,data in enumerate(kf, start=1):
print '{:^9}{}{:^25}'.format(iteration, data[0], data[1])
My question, however, is about the formatting used within print: What does the {:^61}
do, for example? I have never seen the ^
within the braces used for print formatting. It is usually sth like {0:3.2f}
. I know that ^
can be used as XOR, but, what is it doing here?
Can somebody explain?
It centers the text within the field, where the field is 61 characters wide.
This is documented in the Format Specification Mini-Language:
'^'
Forces the field to be centered within the available space.
Note that there are also options for left and right alignment (using '<'
and '>'
, respectively), as well as a number-specific =
option to put the padding between the value and the positive or negative sign.
Different object types have different formatting specifications; Python essentially takes the part after :
from {...:...}
and delegates the formatting to the object being formatted, via the __format__()
method. So while numbers support specifications like 3.2f
, there many more possible formatting specifiers. For example, datetime.date()
, datetime.date()
and datetime.time()
objects take strftime()
formatting specification strings, and you can implement your own in custom Python classes.