1

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.

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.