Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 563
user2856069 Avatar asked Oct 18 '25 20:10

user2856069


2 Answers

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

like image 85
Felipe Avatar answered Oct 20 '25 11:10

Felipe


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

like image 24
Guy Avatar answered Oct 20 '25 09:10

Guy