Python 3 - 在 str.format() 中使用元组 [英] Python 3 - using tuples in str.format()

查看:43
本文介绍了Python 3 - 在 str.format() 中使用元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后我得到 'x1y2z3' - 没问题.
但是,当我尝试:

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

我明白

IndexError: 元组索引超出范围.

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

解决方案

使用 *arg 可变参数调用语法:

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

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)

演示:

<预><代码>>>>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'

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?

解决方案

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'

这篇关于Python 3 - 在 str.format() 中使用元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆