IndexError: tuple index out of range with arguments to the analysis method

I already checked this question, but did not find the answer there. Here is a simple example demonstrating my use case:

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

And the conclusion:

 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: I already refused to use such a method (which wraps str.format() ), since it seems superfluous. But still it puzzles me, why not work as expected?

+7
python string-formatting
source share
3 answers

you need to use * to unzip the tuple into the actual arguments for format :

 print(message.format(*arguments)) 

Otherwise, arguments considered as the only format argument (and it works for the first occurrence of {} by converting your tuple to a string, but throttles when it encounters the second occurrence {} )

+9
source share

You need to pass arguments without a tuple. This is done using '* arguments'. Extension of tuples in 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") 
+1
source share

try it

 print(message.format(*arguments)) 

format does not expect a tuple

0
source share

All Articles