Python 3 - 在str.format()中使用元组

sou*_*alo 8 python string tuples string-formatting

我正在尝试使用该str.format()方法,并且当我的值存储在元组中时遇到一些困难.例如,如果我这样做:

s = "x{}y{}z{}"
s.format(1,2,3)
Run Code Online (Sandbox Code Playgroud)

然后我明白了'x1y2z3'- 没问题.
但是,当我尝试:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(tup)
Run Code Online (Sandbox Code Playgroud)

我明白了

IndexError: tuple index out of range.
Run Code Online (Sandbox Code Playgroud)

那么如何将元组转换为单独的变量呢?或任何其他解决方法的想法?

Mar*_*ers 21

使用*arg变量参数调用语法传入元组:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(*tup)
Run Code Online (Sandbox Code Playgroud)

*之前tup告诉Python中的元组解压到单独的参数,就好像你打电话s.format(tup[0], tup[1], tup[2])吧.

或者您可以索引第一个位置参数:

s = "x{0[0]}y{0[1]}z{0[2]}"
tup = (1,2,3)
s.format(tup)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> tup = (1,2,3)
>>> s = "x{}y{}z{}"
>>> s.format(*tup)
'x1y2z3'
>>> s = "x{0[0]}y{0[1]}z{0[2]}"
>>> s.format(tup)
'x1y2z3'
Run Code Online (Sandbox Code Playgroud)