Python 3 - using tuples in str.format() [duplicate]

≯℡__Kan透↙ 提交于 2019-12-05 22:07:16

问题


I'm trying to use the str.format() method, and having some difficulties when my values are stored within a tuple. For example, if I do:

s = "x{}y{}z{}"
s.format(1,2,3)

Then I get 'x1y2z3' - no problem.
However, when I try:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(tup)

I get

IndexError: tuple index out of range.

So how can I 'convert' the tuple into separate variables? or any other workaround ideas?


回答1:


Pass in the tuple using *arg variable arguments call syntax:

s = "x{}y{}z{}"
tup = (1,2,3)
s.format(*tup)

The * before tup tells Python to unpack the tuple into separate arguments, as if you called s.format(tup[0], tup[1], tup[2]) instead.

Or you can index the first positional argument:

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

Demo:

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



回答2:


You can unpack the contants of the tuple.

s=s.format(*t)



来源:https://stackoverflow.com/questions/26758341/python-3-using-tuples-in-str-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!