>>> 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'
这就避免了在末尾构建包含一个额外元素的新元组的需要。