just user
just user

Reputation: 13

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: tuple index out of range

The code:

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

The tuple contains two strings with indexes 0 and 1 and this error should not be displayed.

Upvotes: 1

Views: 15198

Answers (2)

VPfB
VPfB

Reputation: 17247

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)

Upvotes: 0

arcyqwerty
arcyqwerty

Reputation: 10675

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)

Upvotes: 9

Related Questions