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!
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])
).
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With