2017-01-13 132 views
7

我已經檢查了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())已經拒絕了,因爲它似乎是過剩的。但它仍令我困惑,爲什麼不按預期工作?

回答

9

你必須使用*來把它解析成實際的論據format

print(message.format(*arguments)) 

否則,arguments被視爲格式的唯一的參數(和它的作品的第{}發生,通過轉換你的元組到字符串,但扼流器遇到第二次出現時{}

1

您需要傳遞參數而不是元組。這是通過使用'*參數'來完成的。 Expanding tuples into arguments

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(type(arguments)) 
    print(message.format(*arguments)) 

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

試試這個

print(message.format(*arguments)) 

format不指望一個元組

+0

你是對的,但'arguments'是一個元組:) – ppasler

+0

@ppasler,哎呀呀。當然,你是對的。 – user650881