我希望能够以某种方式格式化数字,并且对于我调用的每个打印函数都这样,而不是在每个打印函数中重新格式化它。我只是把它看作是一种清理代码的方法。这是一个例子:
鉴于变量:
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
语句中,但正如您所看到的,无论哪种方式,我都必须每次格式化相同的变量。我怎么能避免这个?
答案 0 :(得分:1)
如何提取常见格式代码有很多选项,例如:
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'))
(请注意,新格式样式如何让生活更轻松。)
答案 1 :(得分:0)
将其格式化一次,将格式化的字符串存储在变量中,然后使用该变量。
答案 2 :(得分:0)
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))
甚至更好:
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')