我正在努力做到以下几点:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
但是,我有一个很长的x
,超过两个项目,所以我试过:
>>> '%d,%d,%s' % (*x, y)
但这是语法错误。如果不像第一个例子那样编制索引,这样做的正确方法是什么?
str % ..
接受一个元组作为右手操作数,因此您可以执行以下操作:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
你的尝试应该在Python 3中工作。支持Additional Unpacking Generalizations
,但不支持Python 2.x:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
也许看看str.format()。
>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'
为了完整起见,我还要包括PEP 448描述的其他拆包概括。扩展语法是在Python 3.5中引入的,以下不再是语法错误:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {}'
>>> template.format(*x, y) # valid in Python3.5+
'first: 5, second: 7, last: 42'
但是,在Python 3.4及更低版本中,如果要在解压缩后的元组之后传递其他参数,最好将它们作为命名参数传递:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {last}'
>>> template.format(*x, last=y)
'first: 5, second: 7, last: 42'
这避免了在最后构建包含一个额外元素的新元组的需要。
我建议你使用str.format
而不是str %
,因为它“更现代”,并且还有更好的功能集。那说你想要的是:
>>> x = (1,2)
>>> y = 'hello'
>>> '{},{},{}'.format(*(x + (y,)))
1,2,hello
对于format
的所有酷炫功能(以及一些与%
相关的功能),请查看PyFormat。