zjm*_*126 160 python python-2.x
这是我的代码:
print str(float(1/3))+'%'
Run Code Online (Sandbox Code Playgroud)
它显示:
0.0%
Run Code Online (Sandbox Code Playgroud)
但我想得到 33%
我能做什么.
mik*_*iku 246
>>> print "{0:.0%}".format(1./3)
33%
Run Code Online (Sandbox Code Playgroud)
如果您不想进行整数除法,可以从__future__
以下位置导入Python3的除法:
>>> 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%
Run Code Online (Sandbox Code Playgroud)
小智 165
格式化方法有一种更方便的'百分比'格式化选项.format()
:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
Run Code Online (Sandbox Code Playgroud)
Mes*_*ion 61
仅仅为了完整起见,我注意到没有人建议这个简单的方法:
>>> print("%.0f%%" % (100 * 1.0/3))
33%
Run Code Online (Sandbox Code Playgroud)
细节:
%.0f
代表" 打印带小数点后0位的浮点数 ",因此%.2f
会打印33.33
%%
打印文字%
.比你原来的一点清洁+'%'
1.0
而不是1
照顾强迫分裂浮动,所以不再0.0
men*_*rfa 45
只是为了添加 Python 3 f-string 解决方案
prob = 1.0/3.0
print(f"{prob:.0%}")
Run Code Online (Sandbox Code Playgroud)
Yuj*_*ita 36
你正在划分整数然后转换为浮点数.除以花车代替.
作为奖励,使用这里描述的令人敬畏的字符串格式化方法: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%'
Run Code Online (Sandbox Code Playgroud)
一个伟大的宝石!
那么你会想要这样做:
print str(int(1.0/3.0*100))+'%'
Run Code Online (Sandbox Code Playgroud)
将.0
它们表示为浮点数,int()
然后再次将它们舍入为整数。