开发者

Expanding tuples in python

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 do开发者_如何学Goesn'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


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,))
#                                  ^^^^^^^^^^^^^^^^^


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.


>>> 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜