首页 > 解决方案 > .format 中的元组索引超出范围

问题描述

我有两个要打印的论点

print('{0:25}${2:>5.2f}'.format('object', 20))

但他们给出了以下回应:

Traceback (most recent call last):

IndexError: tuple index out of range

但是当我将代码更改为以下内容时,我得到了所需的输出:

print('{0:25}${2:>5.2f}'.format('object', 20, 20))

我不明白为什么,因为我只有两组 {}。谢谢

标签: python-3.xformattuples

解决方案


您的问题是 $ 符号后的 2 索引:

print('{0:25}${2:>5.2f}'.format('object', 20, 20))

当您在 python 中的字符串上使用 .format 时,数字 at{number:}是您想要的参数的索引。例如以下:

"hello there {1:} i want you to give me {0:} dollars".format(2,"Tom")

将导致以下输出:

'hello there Tom i want you to give me 2 dollars'

这里有一个简单的例子: https ://www.programiz.com/python-programming/methods/string/format

总而言之,为了让您的代码正常工作,只需使用:

print('{0:25}${1:>5.2f}'.format('object', 20))

推荐阅读