'IndexError: tuple index out of range' whith str.format

'IndexError: tuple index out of range' whith str.format

我做错了什么?

print('script executed in {time}{1:.2f} seconds'.format(time=elapsed_time))

我得到:

IndexError: tuple index out of range

预期输出:

script executed in 0.12 seconds

您创建了两个格式字段:

print('script executed in {time}{1:.2f} seconds'.format(time=elapsed_time))
#                         ^1    ^2

但只给str.format一个参数:

print('script executed in {time}{1:.2f} seconds'.format(time=elapsed_time))
#                                                       ^1

您需要使格式字段的数量与参数的数量相匹配:

print('script executed in {time:.2f} seconds'.format(time=elapsed_time))

你可以做到

>>> 'script executed in {:.2f} seconds'.format(elapsed_time)
'script executed in 0.12 seconds'

在您的原始代码中,您有两个 {} 字段,但只给出了一个参数,这就是它给出 "tuple index out of range" 错误的原因。