为什么格式化会导致print()失败?

时间:2015-05-20 21:53:04

标签: python python-3.x

我创建了一个名为P1Puts [] []的二维数组。我想用它做的一切都很好,直到格式化输出。任何人都可以告诉我为什么我尝试格式化输出导致错误“元组索引超出范围”?我使用实时数据从shell创建了以下示例。请注意,“第1次试验2”工作正常,但“第2次试验2”会产生错误。

#=================================================
# TRIAL 1 OF 2:

>>> 
>>> for r in range(9):
    print('r',r,P1Puts[r][2])


r 0 51.73
r 1 51.8
r 2 60.46
r 3 34.62
r 4 49.69
r 5 87.93
r 6 33.37
r 7 42.59
r 8 54.6
>>> 
#=================================================
# TRIAL 2 OF 2: 
# (Note that all I did below was add formatting
#  to the third argument in print()

>>> for r in range(9):
    print('r',r,"{6.2f}".format(P1Puts[r][2]))


Traceback (most recent call last):
  File "<pyshell#21>", line 2, in <module>
    print('r',r,"{6.2f}".format(P1Puts[r][2]))
IndexError: tuple index out of range
>>> 

1 个答案:

答案 0 :(得分:4)

您错过了:

for r in range(9):
    print('r',r,"{:6.2f}".format(P1Puts[r][2])) # : ← missing