当前位置:  开发笔记 > 编程语言 > 正文

IndexError:解析方法参数时,元组索引超出范围

如何解决《IndexError:解析方法参数时,元组索引超出范围》经验,为你挑选了1个好方法。

我已经检查了这个问题,但在那里找不到答案.这是一个演示我的用例的简单示例:

def log(*args):
    message = str(args[0])
    arguments = tuple(args[1:])
    # message itself
    print(message)
    # arguments for str.format()0
    print(arguments)
    # shows that arguments have correct indexes
    for index, value in enumerate(arguments):
        print("{}: {}".format(index, value))
    # and amount of placeholders == amount of arguments
    print("Amount of placeholders: {}, Amount of variables: {}".format(message.count('{}'), len(arguments)))

    # But this still fails! Why?
    print(message.format(arguments))

log("First: {}, Second: {}, Third: {}, Fourth: {}", "asdasd", "ddsdd", "12312333", "fdfdf")

并输出:

First: {}, Second: {}, Third: {}, Fourth: {}
('asdasd', 'ddsdd', '12312333', 'fdfdf')
0: asdasd
1: ddsdd
2: 12312333
3: fdfdf
Amount of placeholders: 4, Amount of variables: 4
Traceback (most recent call last):
  File "C:/Users/sbt-anikeev-ae/IdeaProjects/test-this-thing-on-python/test-this-thing.py", line 12, in 
    log("First: {}, Second: {}, Third: {}, Fourth: {}", "asdasd", "ddsdd", "12312333", "fdfdf")
  File "C:/Users/sbt-anikeev-ae/IdeaProjects/test-this-thing-on-python/test-this-thing.py", line 10, in log
    print(message.format(arguments))
IndexError: tuple index out of range

PS:我已经拒绝使用这种方法(包装str.format()),因为它似乎是多余的.但它仍然困扰我,为什么这不会像预期的那样工作?



1> Jean-Françoi..:

你必须使用*将元组解压缩为实际参数format:

print(message.format(*arguments))

否则,arguments被视为格式的唯一参数(并且它适用于第一次{}出现,通过将您的元组转换为字符串,但在遇到第二次出现时扼流圈{})

推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有