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!

nucsit026
  • 652
  • 7
  • 16

4 Answers4

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])).

ruohola
  • 21,987
  • 6
  • 62
  • 97
felipe
  • 7,324
  • 2
  • 28
  • 37
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.

Guy
  • 46,488
  • 10
  • 44
  • 88
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 *

Mohit Chandel
  • 1,838
  • 10
  • 31
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)
abhiarora
  • 9,743
  • 5
  • 32
  • 57