Python:打印表达式中 ^ 运算符的用法:{^:61}.format

Python: Usage of ^ operator within a print expression: {^:61}.format

我正在观看有关交叉验证概念的视频。这是该视频的代码片段:

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])

但是,我的问题是关于打印中使用的格式:例如,{:^61} 有什么作用?我从未在用于打印格式的大括号内看到 ^ 。通常是 {0:3.2f} 之类的东西。我知道 ^ 可以用作 XOR,但是,它在这里做什么?

有人可以解释一下吗?

它使文本在字段中居中,字段宽度为 61 个字符。

这记录在 Format Specification Mini-Language:

'^'
Forces the field to be centered within the available space.

请注意,还有用于左右对齐的选项(分别使用 '<''>'),以及用于放置填充的数字特定 = 选项在值和正负号之间。

不同的对象类型有不同的格式规范; Python 本质上是 {...:...} : 之后的部分,并通过 __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 将格式化委托给正在格式化的对象,您可以在自定义 [=33] 中实现自己的=] 类.