这是我的代码:
print str(float(1/3))+'%'
它显示:
0.0%
但是我想得到33%
我该怎么办?
[format
支持百分比format
:
floating point precision type
如果不想整数除法,可以从>>> print "{0:.0%}".format(1./3)
33%
导入Python3的除法:
__future__
__future__
格式方法有一种更方便的'percent'格式选项:
>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
只是为了完整起见,因为我注意到没有人建议使用这种简单方法:
.format()
详细信息:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
代表“ 打印带有0个小数位的浮点数”,因此>>> print("%.0f%%" % (100 * 1.0/3))
33%
将打印%.0f
%.2f
打印文字33.33
。比原始的%%
]更干净%
而不是+'%'
负责强制除法浮点运算,因此不再需要1.0
您将整数相除,然后转换为浮点数。用浮点数代替。
然后您要执行此操作:
只需添加Python 3 f字符串解决方案
就像这样放:
如何这样:
这是我的做法: