本文介绍了如何将元组传递给 str.format()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 str.format() 函数来打印列中的矩阵.

这是出错的行:

>>>>"{!s:4}{!s:5}".format('j',4,3)'j 4'>>>>"{!s:4}{!s:5}".format(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中IndexError:元组索引超出范围>>>乙('dat', '是')

我做错了什么?

我想我知道问题是什么:我传递了一个包含两个元素的元组,而不是作为一个包含一个元素的元组传递给函数,我的原始元组.因此出现此错误.所以问题是如何将此元组传递给格式函数...

解决方案

如果你能确定元组的长度,你可以解包它.

>>>"{!s:4}{!s:5}".format(*b)'j 4'

I'm trying to use the str.format() function to print a matrix in columns.

This is the line that goes wrong:

>>>> "{!s:4}{!s:5}".format('j',4,3)
'j   4    '
>>>> "{!s:4}{!s:5}".format(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> b
('dat', 'is')

What am I doing wrong?

Edit:I think I know what the problem is: I'm passing a tuple with two elements, which is than passed on to the function as a tuple with one element, my original tuple. Hence this error. so the question is rather how to pass this tuple to the format function...

解决方案

You can unpack the tuple if you can be certain of its length.

>>> "{!s:4}{!s:5}".format(*b)
'j   4    '

这篇关于如何将元组传递给 str.format()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:52
查看更多