添加值时的格式语法

时间:2018-11-16 18:25:45

标签: python-3.7

我正在尝试使用format()将一个元组的几个值加在一起。我编写了一个函数,该函数返回具有12个值的元组。

我的元组看起来像这样:

In[86]results Out[86]: (15.24, 2527.4, 2812.59, 7.87, 2389.72, 1795.39, 594.33, 98.34, 68.84, 60.0, 132, 5)

我一直在这样打印到标准输出(基于format examples from docs.python.org):

print('-Sponge Yeast: {0[0]}g'.format(results))

print('-Sponge Flour: {0[1]}g'.format(results))

print('-Sponge Water: {0[2]}g'.format(results))

我要打印另一行,它是结果中前三个值的总和。

过去,我可以这样做:

print('-Total Sponge Weight: {:n}g'.format(a+b+c)) 其中a,b,c ...,i分别等于12个值。

我不想为元组的12个值创建12个变量,而是要为元组使用一个变量。但是,如何在元组中求和几个值并使用format()?我尝试过:

print('-Total Sponge Weight: {0[0] + 0[1] + 0[2]}g'.format(results))

print('-Total Sponge Weight: {:n}g'.format(0.results + 1.results + 2.results))

但这不起作用。我知道我可以简单地使函数输出正确的值,并且可以将其称为{0 [xx]}。只是想知道是否还有另一种方法。

2 个答案:

答案 0 :(得分:0)

您也许可以使用pprint。我自己从未使用过它,但是它是为格式化打印数据而设计的。

答案 1 :(得分:0)

使用Python 3的f字符串,这很容易。

values = (1, 2, 3)

In[1]: f'The sum of values is {values[0]+values[1]+values[2]}!

Out[1]: 'The sum of values is 6!