【问题标题】:Tuple index out of range in .format.format 中的元组索引超出范围
【发布时间】:2018-11-12 21:23:00
【问题描述】:

我有两个要打印的参数

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.x format tuples


    【解决方案1】:

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

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

    当您在 python 中的字符串上使用 .format 时,{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))
    

    【讨论】:

    • 或者通过排除显式位置参数来使用自动编号,例如:'{:25}${:>5.2f}'
    【解决方案2】:

    应该是

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

    注意占位符从2更改为1

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

    当你添加第三个参数(第二个20)时,占位符2会找到一个值

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

    但是没有第三个参数,会抛出index out of range异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2021-03-02
      • 2018-11-16
      • 2016-04-04
      • 2020-06-08
      • 2017-07-12
      相关资源
      最近更新 更多