+ 1
Why this code runs?: nums = [4, 5, 6] msg = "Numbers: {} {}". format(nums[0], nums[1], nums[2]) print(msg) Numbers:4, 5. Byt the code: nums = [4, 5, 6] msg = "Numbers: {} {} {} {}". format(nums[0], nums[1], nums[2]) print(msg) leading to error? IndexError: tuple index our of range
3 odpowiedzi
+ 7
Remove a {} in the second code.
+ 4
Zen's answer fixes the code; for 'why' (because what tuple could it possibly be referencing?)....
Python seems to count {}'s, convert the parameter list to a tuple and iterate with the count. See this alternate way to pass parameters:
>>> n=[1,2,3,4]
>>> m="{} {} {} {}".format(*n)
>>> m
'1 2 3 4'
To me this is a bug, because the actual error (IMO) should be:
"format string takes exactly 4 arguments (3 given)"
0
@Kirk Schafer, Thank you!