12

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?

2
  • You are actually passing a single argument that is a tuple. Commented Nov 5, 2014 at 13:26
  • def fun(*args): print('My args: {!a}'.format(args)) I just don't know yet what 'a' means, but it seems to be a 'conversion specifier'. I've also seen the use of 'r'. Commented Oct 20, 2019 at 16:17

2 Answers 2

32

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' 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! it worked, but can you explain more what's actually going on with the *? or refer me to the right place in the documentation?
This really helpful if used inside map() and you don't want to define lambda or custom function to use * to unpack the tuple! This is the only solution (that I could find) that talks about indexing in format to unpack tuple. Cheers!
-3

You can unpack the contants of the tuple.

s=s.format(*t)

3 Comments

This doesn't seem to add anything not already covered in an existing answer.
@Kevin - So downvote it. Don't flag it.
shorter is better

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.