Python 虽然我插入了不同的字符串,str.format打印相同的字符串

Python 虽然我插入了不同的字符串,str.format打印相同的字符串,python,python-2.6,Python,Python 2.6,我想用特定的对齐方式在一行中打印不同的变量。但是,str.format打印相同的字符串 下面是我所做的和输出的代码 我想打印 >>> print("{0:^20} {0:^20} {0:^40}\n".format('chkitem', 'Count', 'Coordinate')) chkitem Count Coordinate 有什么问题 print(&

我想用特定的对齐方式在一行中打印不同的变量。但是,str.format打印相同的字符串

下面是我所做的和输出的代码

我想打印

>>> print("{0:^20} {0:^20} {0:^40}\n".format('chkitem', 'Count', 'Coordinate'))
      chkitem              Count                        Coordinate       
有什么问题

print("{:^20} {:^20} {:^40}\n".format('chkitem', 'Count', 'Coordinate'))
冒号前的零指定使用零索引格式参数,如果省略它们,将默认使用提供的下一个格式参数


您还可以指定
0:
1:
2:
等等,但最佳做法是,如果要多次打印参数,则只指定索引。

{0:^20}-0是项在格式参数中的位置。你必须增加它

print("{0:^20} {1:^20} {2:^40}\n".format('chkitem', 'Count', 'Coordinate'))

打印({0:^20}{1:^20}{2:^40}\n)。格式('chkitem','Count','Coordinate'))我强烈建议使用更新的解释器。在Python>=3.6的更高版本中,您可以更友好地使用f字符串:
print(f“{'chkitem':^20}{'Count':^20}{'Coordinate':^40}\n”)
感谢您的回答。我解决了这个问题:)谢谢。
print("{0:^20} {1:^20} {2:^40}\n".format('chkitem', 'Count', 'Coordinate'))