Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 - using tuples in str.format() [duplicate]

I'm trying to use the str.format() method, and having some difficulties when my values are stored within a tuple. For example, if I do:

s = "x{}y{}z{}"
s.format(1,2,3)

Then I get 'x1y2z3' - no problem.
However, when I try:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(tup)

I get

IndexError: tuple index out of range.

So how can I 'convert' the tuple into separate variables? or any other workaround ideas?

like image 296
soungalo Avatar asked Nov 05 '14 13:11

soungalo


People also ask

Can tuples have duplicates in Python?

Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

How do you find duplicates in tuple?

Initial approach that can be applied is that we can iterate on each tuple and check it's count in list using count() , if greater than one, we can add to list. To remove multiple additions, we can convert the result to set using set() .

How do you repeat a tuple element in Python?

We can use + operator to combine two tuples. This is called concatenation. We can also repeat the elements in a tuple for a given number of times using the * operator.

Can tuples be replicated?

By using the * operator we can replicate our tuples by the number of times we specify, creating new tuples based on the original data sequence. Existing tuples can be concatenated or multiplied to form new tuples through using the + and * operators.


1 Answers

Pass in the tuple using *arg variable arguments call syntax:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(*tup)

The * before tup tells Python to unpack the tuple into separate arguments, as if you called s.format(tup[0], tup[1], tup[2]) instead.

Or you can index the first positional argument:

s = "x{0[0]}y{0[1]}z{0[2]}"
tup = (1,2,3)
s.format(tup)

Demo:

>>> tup = (1,2,3)
>>> s = "x{}y{}z{}"
>>> s.format(*tup)
'x1y2z3'
>>> s = "x{0[0]}y{0[1]}z{0[2]}"
>>> s.format(tup)
'x1y2z3'
like image 103
Martijn Pieters Avatar answered Nov 06 '22 02:11

Martijn Pieters