str.format() -> 如何左对齐

11
>>> print 'there are {0:10} students and {1:10} teachers'.format(scnt, tcnt)
there are        100 students and         20 teachers

代码应该怎样编写才能使输出变为:

there are 100        students and 20         teachers

谢谢。

1个回答

22
print 'there are {0:<10} students and {1:<10} teachers'.format(scnt, tcnt)

虽然旧的%操作符使用-进行对齐,但新的format方法使用<>


1
为了完整性,使用 <> 来左对齐和右对齐,而不仅仅是一个 - 标志,可以允许额外的对齐格式代码,例如 ^ 用于居中对齐。请参见 格式规范迷你语言 - AJNeufeld

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接