user2856069
user2856069

Reputation: 61

Using tuples with .format in python

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!

Upvotes: 4

Views: 1386

Answers (4)

abhiarora
abhiarora

Reputation: 10430

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)

Upvotes: 0

Guy
Guy

Reputation: 50819

@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.

Upvotes: 3

Mohit Chandel
Mohit Chandel

Reputation: 1916

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 *

Upvotes: 1

felipe
felipe

Reputation: 8025

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

Upvotes: 8

Related Questions