4

while using the .format() with text filling, I encounter this error.

what I have:

tuple = ('a', 'b', 'c')
text = "Hi {} hello {} ola {}"
#command I tried to run
text.format(tuple)

The output I am aiming for:

 Hi a hello b ola c

the error I get:

IndexError: tuple index out of range

not sure how to fix this!

2
  • 3
    Unpack the tuple. ie, text.format(*tuple) Commented Jan 27, 2020 at 6:39
  • Does this answer your question? Expanding tuples into arguments Commented Jan 28, 2020 at 10:24

4 Answers 4

8

You want to use an iterable unpacking:

>>> t = (1, 2, 3)
>>> "{}, {}, {}".format(*t)
'1, 2, 3'

Side note: Do not use tuple as a variable name, as that is a reserved Python built-in function (i.e. tuple([1, 2, 3])).

Sign up to request clarification or add additional context in comments.

1 Comment

@FelipeFaria I'm sorry, but your terminology needs some updating :)
3

@FelipeFaria's answer is the correct solution, the explanation is that in text.format(tuple) you are essentially adding the entire tuple to the first place holder

print(text.format(tuple))

if worked, will print something like

Hi (a, b, c) hello { } ola { }

format is expecting 3 values, since it found only one it raise tuple index out of range exception.

Comments

1

I agreed to the previous answer "do not use a tuple as a variable name,". I modified your code now you can try this. It will be easier to understand.

tup = ('a', 'b', 'c')
text = "Hi {} hello {} ola {}"
tex = text.format(*tup)
print(tex)

and for unpacking the tuple you should add *

Comments

0

See this question for How to unpack a tuple in Python.

I am quoting one of the answer:

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too.

For you, you can try (as mentioned in one of the answer, you should avoid using any reserved keyword for your variables and methods):

t = ('a', 'b', 'c')
text = "Hi {} hello {} ola {}".format(*t)
print(text)

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.