【问题标题】:'IndexError: tuple index out of range' whith str.format'IndexError:元组索引超出范围'带有str.format
【发布时间】:2015-01-08 15:10:06
【问题描述】:

我做错了什么?

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

我明白了:

IndexError: tuple index out of range

预期输出:

script executed in 0.12 seconds

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    您创建了两个格式字段:

    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))
    

    【讨论】:

    • 感谢您的详细解释。点赞并接受。
    • 奇怪的错误信息。它暗示 Python 使用元组进行参数传递,但事实并非如此。
    【解决方案2】:

    你可以这样做

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

    在您的原始代码中,您有两个 {} 字段,但只给出了一个参数,这就是它给出“元组索引超出范围”错误的原因。

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 2018-11-16
      • 2017-07-12
      • 2013-12-16
      • 2021-12-21
      • 2014-08-01
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多