我正努力做到以下几点:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
然而,我有一个长长的x
多个项目,所以我try 了:
>>> '%d,%d,%s' % (*x, y)
但这是语法错误.在没有像第一个例子那样索引的情况下,正确的方法是什么?
我正努力做到以下几点:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
然而,我有一个长长的x
多个项目,所以我try 了:
>>> '%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'
您的try 应该可以在Python 3中使用.其中支持Additional Unpacking Generalizations
,但Python 2中不支持.x:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'