我已經檢查了this問題,但在那裏找不到答案。下面是一個說明我的情況下,使用一個簡單的例子:IndexError:解析方法參數時元組索引超出範圍
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 <module>
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()
)已經拒絕了,因爲它似乎是過剩的。但它仍令我困惑,爲什麼不按預期工作?
你是對的,但'arguments'是一個元組:) – ppasler
@ppasler,哎呀呀。當然,你是對的。 – user650881