tags:

views:

147

answers:

3

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
+3  A: 

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
I'd rather `'{0}{2}{3}{1}'.format(a,b,*tup)`.
KennyTM
+1, i'll change the post
aaronasterling
+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
+6  A: 

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,))
#                                  ^^^^^^^^^^^^^^^^^
KennyTM
+1  A: 
>>> 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
gnibbler