如何在python中打印百分比值?

问题描述 投票:160回答:9

这是我的代码:

print str(float(1/3))+'%'

它显示:

0.0%

但是我想得到33%

我该怎么办?

python python-2.x
9个回答
244
投票

[format支持百分比format

floating point precision type

如果不想整数除法,可以从>>> print "{0:.0%}".format(1./3) 33% 导入Python3的除法:

__future__

164
投票

__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%

61
投票

只是为了完整起见,因为我注意到没有人建议使用这种简单方法:

.format()

详细信息:

  • >>> '{:.1%}'.format(1/3.0) '33.3%' 代表“ 打印带有0个小数位的浮点数”,因此>>> print("%.0f%%" % (100 * 1.0/3)) 33% 将打印%.0f
  • %.2f打印文字33.33。比原始的%%]更干净
  • [%而不是+'%'负责强制除法浮点运算,因此不再需要1.0

36
投票

您将整数相除,然后转换为浮点数。用浮点数代替。


4
投票

然后您要执行此操作:


3
投票

只需添加Python 3 f字符串解决方案


0
投票

就像这样放:


-2
投票

如何这样:


-3
投票

这是我的做法:

© www.soinside.com 2019 - 2024. All rights reserved.