Python 输出百分比的两种方式
注: 在python3环境下测试。
方式1:直接使用参数格式化:{:.2%}
{:.2%}: 显示小数点后2位
- 显示小数点后2位:
>>> print('percent: {:.2%}'.format(42/50)) percent: 84.00%
- 不显示小数位:
{:.0%},即,将2改为0:
>>> print('percent: {:.0%}'.format(42/50)) percent: 84%
方式2:格式化为float,然后处理成%格式: {:.2f}%
与方式1的区别是:
(1) 需要对42/50乘以 100 。
(2) 方式2的%在{ }外边,方式1的%在{ }里边。
- 显示小数点后2位:
>>> print('percent: {:.2f}%'.format(42/50*100)) percent: 84.00%
- 显示小数点后1位:
>>> print('percent: {:.1f}%'.format(42/50*100)) percent: 84.0%
- 只显示整数位:
>>> print('percent: {:.0f}%'.format(42/50*100)) percent: 84%
说明
{ } 的意思是对应format()的一个参数,按默认顺序对应,参数序号从0开始,{0}对应format()的第一个参数,{1}对应第二个参数。例如:
- 默认顺序:
>>> print('percent1: {:.2%}, percent2: {:.1%}'.format(42/50, 42/100)) percent1: 84.00%, percent2: 42.0%
- 指定顺序:
{1:.1%}对应第2个参数;{0:.1%}对应第1个参数。
>>> print('percent2: {1:.1%}, percent1: {0:.1%}'.format(42/50, 42/100)) percent2: 42.0%, percent1: 84.0%
Python2 中输出百分比
在 Python2 中,计算 42/50 的结果是 0,所以,需要把 int 类型转换成 float 类型,计算出正确的结果后,再以百分比的形式输出。
情形1:已经有固定的数字,例如 50,在后面加 .0 变为 50.0
情形2:分子分母都是计算出来的结果,转成 float 类型,例如 float(42)/50, 42/float(50)
举例: {:.2%}
>>> print('percent: {:.2%}'.format(42/50)) percent: 0.00% >>> print('percent: {:.2%}'.format(42.0/50)) percent: 84.00% >>> print('percent: {:.2%}'.format(42/50.0)) percent: 84.00% >>> print('percent: {:.2%}'.format(float(42)/50)) percent: 84.00% >>> print('percent: {:.2%}'.format(42/float(50))) percent: 84.00%
举例:{:.2f}%
>>> print('percent: {:.2f}%'.format(42/50*100)) percent: 0.00% >>> print('percent: {:.2f}%'.format(42.0/50*100)) percent: 84.00% >>> print('percent: {:.2f}%'.format(42/50.0*100)) percent: 84.00% >>> print('percent: {:.2f}%'.format(float(42)/50*100)) percent: 84.00% >>> print('percent: {:.2f}%'.format(42/float(50)*100)) percent: 84.00%
这些输出 0.00% 的原因是 42/50 的结果是 0,所以最终输出 0.00% 。
>>> print('percent: {:.2%}'.format(42/50)) percent: 0.00% >>> print('percent: {:.2f}%'.format(42/50*100)) percent: 0.00% >>> print('percent: {:.2f}%'.format(42/50*100.0)) percent: 0.00%
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/202170.html原文链接:https://javaforall.net
