Skip to content Skip to sidebar Skip to footer

Python 3 Format Method - Tuple Index Out Of Range

I have a problem with the format method in Python 3.4.2. Shows me the following error: Traceback (most recent call last): Python Shell, prompt 2, line 3 builtins.IndexError: tup

Solution 1:

According to the docs you should be passing in the arguments as positional arguments, not as a tuple. If you want to use the values in a tuple, use the * operator.

str.format(*args, **kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

"The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3'

More specifically, you'd want to do the following:

A = "{0}={1}"
B = ("str", "string")
C = A.format(*B)
print (C)

or

A = "{0}={1}"
C = A.format("str", "string")
print (C)

Solution 2:

You have to unpack the tuple to have two arguments instead of one tuple:

A = "{0}={1}"
B = ("str", "string")
C = A.format(*B)
print (C)

Or modify your format string to accept one argument with two elements in a sequence.

A = "{0[0]}={0[1]}"
B = ("str", "string")
C = A.format(B)
print (C)

Post a Comment for "Python 3 Format Method - Tuple Index Out Of Range"