2

In the following code:

a = 'a'
tup = ('tu', 'p')
b = 'b'
print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b)

How can I "expand" (can't figure out a better verb) tup so that I don't have to explicitly list all its elements?

NOTE That I don't want to print tup per-se, but its individual elements. In other words, the following code is not what I'm looking for

>>> print 'a: %s, tup: %s, b: %s' % (a, tup, b)
a: a, tup: ('tu', 'p'), b: b

The code above printed tup, but I want to print it's elements independently, with some text between the elements.

The following doesn't work:

print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup, b)
In [114]: print '%s, %s, %s, %s'%(a, tup, b)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

TypeError: not enough arguments for format string
Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170
  • In Ruby it's called splatting; you'll find more information at http://stackoverflow.com/questions/1141504/name-this-python-ruby-language-construct-using-array-values-to-satisfy-function , but I don't think it's applicable in your specific case. – Xiong Chiamiov Aug 09 '10 at 02:09

3 Answers3

9

It is possible to flatten a tuple, but I think in your case, constructing a new tuple by concatenation is easier.

'a: %s, t[0]: %s, t[1]: %s, b:%s'%((a,) + tup + (b,))
#                                  ^^^^^^^^^^^^^^^^^
Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
3

If you want to use the format method instead, you can just do:

"{0}{2}{3}{1}".format(a, b, *tup)

You have to name every paramater after tup because the syntax for unpacking tuples to function calls using * requires this.

aaronasterling
  • 68,820
  • 20
  • 127
  • 125
  • +1 for the Python 3.0 future-proofing and readability. @bgbg: Look at [Format String Syntax](http://docs.python.org/library/string.html#format-string-syntax) and [Format Specification Mini-Language](http://docs.python.org/library/string.html#format-specification-mini-language). These are my favorite references for using the `.format()` – Kit Aug 08 '10 at 14:12
2
>>> print 'a: {0}, t[0]: {1[0]}, t[1]: {1[1]}, b:{2}'.format(a, tup, b)
a: a, t[0]: tu, t[1]: p, b:b

You can also use named parameters if you prefer

>>> print 'a: {a}, t[0]: {t[0]}, t[1]: {t[1]}, b:{b}'.format(a=a, t=tup, b=b)
a: a, t[0]: tu, t[1]: p, b:b
John La Rooy
  • 295,403
  • 53
  • 369
  • 502