问题:如何在python中打印百分比值?
这是我的代码:
print str(float(1/3))+'%'它显示:
0.0%但我想得到 33%
我能做什么?
回答 0
>>> print "{0:.0%}".format(1./3)
33%如果您不希望整数除法,则可以从导入Python3的除法__future__:
>>> 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%回答 1
格式化方法有一种更方便的“百分比”格式化选项.format():
>>> '{:.1%}'.format(1/3.0)
'33.3%'回答 2
只是为了完整起见,因为我注意到没有人建议这种简单的方法:
>>> print("%.0f%%" % (100 * 1.0/3))
33%细节:
- %.0f代表“ 打印带有0个小数位的浮点数 ”,因此- %.2f将打印- 33.33
- %%打印文字- %。比原来的要干净一点- +'%'
- 1.0而不是- 1强迫分部浮动,所以不再- 0.0
回答 3
您将整数相除,然后转换为浮点数。除以浮点数代替。
另外,请使用此处描述的很棒的字符串格式化方法:http : //docs.python.org/library/string.html#format-specification-mini-language
指定转换百分比和精度。
>>> float(1) / float(3)
[Out] 0.33333333333333331
>>> 1.0/3.0
[Out] 0.33333333333333331
>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'
>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'一个伟大的宝石!
回答 4
只是添加Python 3 f字符串解决方案
prob = 1.0/3.0
print(f"{prob:.0%}")回答 5
然后,您想这样做:
print str(int(1.0/3.0*100))+'%'在.0表示他们的花车和int()事后再发他们的整数。
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

