简体   繁体   English

如何在python3.x中格式化多个打印的数字?

[英]How can I format a number for multiple prints in python3.x?

I want to be able to format a number a certain way and have it turn out this way for each print function I call rather than reformat it within each print function. 我希望能够以某种方式设置数字格式,并使其对我调用的每个打印函数都具有这种格式,而不是在每个打印函数中重新格式化。 I just see it as a way to clean up for code a little. 我只是将其视为清理代码的一种方式。 Here's an example: 这是一个例子:

Given the variable: 给定变量:

weight = mass * conversion_const

and say it comes out to over 2 decimal places. 并说出来超过2位小数。

Then I want to print: 然后我要打印:

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

This is just for an example, it would be in a if statement if I were to create something that needed these responses, but as you can see, either way I would have to format the same variable each time. 这仅是一个示例,如果要创建需要这些响应的内容,它将在if语句中,但是如您所见,无论哪种方式,我每次都必须格式化相同的变量。 How can I avoid this? 如何避免这种情况?

There are quite a few options of how to extract the common formatting code, just for example: 关于如何提取通用格式代码的选择有很多,例如:

ANSWER_FORMAT = 'The mass of the load is {0:,2f} Newtons, which is {1}'
format_answer = ANSWER_FORMAT.format

print(format_answer(right_weight, 'just_right'))
print(format_answer(heavy_weight, 'too heavy'))

(Notice, how the new formatting style can make life easier.) (注意,新的格式化样式如何使生活更轻松。)

格式化一次,将格式化的字符串存储在变量中,然后使用该变量。

weight = "%.2f"%(mass * conversion_const)

print('The mass of the load is %s Newtons, which is too heavy'%(weight))
print('The mass of the load is %s Newtons, which is too light'%(weight))
print('The mass of the load is %s Newtons, which is just right'%(weight))
print('The mass of the load is %s Newtons, which is way to heavy'%(weight))

or even better: 甚至更好:

weight = "The mass of the load is %.2f Newtons, which is "%(mass * conversion_const)

print(weight + 'too heavy')
print(weight + 'too light')
print(weight + 'just right')
print(weight + 'way too heavy')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM