【发布时间】:2015-05-23 18:39:19
【问题描述】:
我希望能够以某种方式格式化一个数字,并让我调用的每个打印函数都以这种方式输出,而不是在每个打印函数中重新格式化它。我只是将其视为一种清理代码的方法。这是一个例子:
给定变量:
weight = mass * conversion_const
并说它的结果超过小数点后 2 位。
那我要打印:
print('The mass of the load is %s Newtons, which is too heavy' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is too light' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is just right' %(format(weight, ',.2f')))
print('The mass of the load is %s Newtons, which is wayy to heavy' %(format(weight, ',.2f')))
这只是一个示例,如果我要创建需要这些响应的东西,它将在 if 语句中,但正如您所见,无论哪种方式,我都必须每次都格式化相同的变量。我怎样才能避免这种情况?
【问题讨论】:
-
为什么不预先计算
format(weight, ',.2f')? -
说实话,没想到这一点,谢谢。
标签: python variables python-3.x printing format