Python,在输出中将所有浮点数打印到小数点后两位
我需要输出 4 个不同的浮点数到小数点后两位。
这就是我的:
print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'
非常不干净,而且看起来很糟糕。有没有办法让输出'%.2f'中出现任何浮动?
注意:使用Python 2.6。
I need to output 4 different floats to two decimal places.
This is what I have:
print '%.2f' % var1,'kg =','%.2f' % var2,'lb =','%.2f' % var3,'gal =','%.2f' % var4,'l'
Which is very unclean, and looks bad. Is there a way to make any float in that out put '%.2f'?
Note: Using Python 2.6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
好吧,我至少会按如下方式清理它:
Well I would atleast clean it up as follows:
格式字符串语法。
https://docs.python.org/3/library/string.html#formatstrings
输出将是:
Format String Syntax.
https://docs.python.org/3/library/string.html#formatstrings
The output would be:
如果您只想将值转换为漂亮的字符串,请执行以下操作:
或者,您也可以打印出问题中的单位:
第二种方法允许您轻松更改分隔符(制表符、空格、换行符等) ) 轻松满足您的需求;分隔符也可以是函数参数,而不是硬编码。
编辑:要使用“名称=值”语法,只需更改列表理解中的按元素操作即可:
If you just want to convert the values to nice looking strings do the following:
Alternatively, you could also print out the units like you have in your question:
The second way allows you to easily change the delimiter (tab, spaces, newlines, whatever) to suit your needs easily; the delimiter could also be a function argument instead of being hard-coded.
Edit: To use your 'name = value' syntax simply change the element-wise operation within the list comprehension:
使用 f 字符串:
或者在您的情况下:
use f-strings:
or in your case:
如果您正在寻找可读性,我相信这就是代码:
If you are looking for readability, I believe that this is that code:
我刚刚发现了 round 函数 - 它在 Python 2.7 中,不确定 2.6 中是否如此。它采用浮点数和 dps 数作为参数,因此 round(22.55555, 2) 给出的结果是 22.56。
I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.
如果您想要让打印操作自动将浮点数更改为仅显示小数点后两位,请考虑编写一个函数来替换“打印”。例如:
使用 fp() 代替 print ...
fp("PI is", 3.14159)
... 代替 ...print "PI is", 3.14159
代码>If what you want is to have the print operation automatically change floats to only show 2 decimal places, consider writing a function to replace 'print'. For instance:
Use fp() in place of print ...
fp("PI is", 3.14159)
... instead of ...print "PI is", 3.14159
不是直接按照你想写的方式,不。 Python 的设计原则之一是“显式优于隐式”(请参阅
import this
)。这意味着最好描述您想要的内容,而不是让输出格式取决于某些全局格式设置或其他内容。当然,您可以以不同的方式格式化代码以使其看起来更好:Not directly in the way you want to write that, no. One of the design tenets of Python is "Explicit is better than implicit" (see
import this
). This means that it's better to describe what you want rather than having the output format depend on some global formatting setting or something. You could of course format your code differently to make it look nicer: