+ 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

16th Oct 2016, 10:28 PM
питер огнекрылый
питер огнекрылый - avatar
3 ответов
+ 7
Remove a {} in the second code.
16th Oct 2016, 11:16 PM
Zen
Zen - avatar
+ 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)"
17th Oct 2016, 2:33 PM
Kirk Schafer
Kirk Schafer - avatar
0
@Kirk Schafer, Thank you!
18th Oct 2016, 11:44 AM
питер огнекрылый
питер огнекрылый - avatar