Python输出百分⽐的两种⽅式
Python 输出百分⽐的两种⽅式
注:在python3环境下测试。
⽅式1:直接使⽤参数格式化:{:.2%}
{:.2%}:显⽰⼩数点后2位
显⽰⼩数点后2位:
>>> print('percent: {:.2%}'.format(42/50))
percent: 84.00%
1
2
不显⽰⼩数位:{:.0%},即,将2改为0:
>>> print('percent: {:.0%}'.format(42/50))
percent: 84%
1
2
⽅式2:格式化为float,然后处理成%格式: {:.2f}%
与⽅式1的区别是:
(1)需要对42/50乘以 100 。
(2)⽅式2的%在{ }外边,⽅式1的%在{ }⾥边。
显⽰⼩数点后2位:
>>> print('percent: {:.2f}%'.format(42/50*100))
percent: 84.00%
1
2
显⽰⼩数点后1位:
>>> print('percent: {:.1f}%'.format(42/50*100))
python格式化输出formatpercent: 84.0%
1
2
只显⽰整数位:
>>> print('percent: {:.0f}%'.format(42/50*100))
percent: 84%
1
2
说明
{ }的意思是对应format()的⼀个参数,按默认顺序对应,参数序号从0开始,{0}对应format()的第⼀个参数,{1}对应第⼆个参数。例如:默认顺序:
>>> print('percent1: {:.2%}, percent2: {:.1%}'.format(42/50, 42/100))
percent1: 84.00%, percent2: 42.0%
1
2
指定顺序:
{1:.1%}对应第2个参数;{0:.1%}对应第1个参数。
>>> print('percent2: {1:.1%}, percent1: {0:.1%}'.format(42/50, 42/100)) percent2: 42.0%, percent1: 84.0%

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。