python输出百分比的两种方式

Python020

python输出百分比的两种方式,第1张

方式1:参数格式化:{:.2%}、{:.1%}、{:.0%}

{:.2%}: 显示小数点后2位

print('percent: {:.2%}'.format(10/50))

percent: 25.00%

print('percent: {:.1%}'.format(10/50))

percent: 25.0%

print('percent: {:.0%}'.format(10/50))

percent: 25%

方式2:先格式化为float,再处理成%格式: {:.2f}%、{:.1f}%、 {:.0f}%

print('percent: {:.2f}%'.format(10/50*100))

percent: 25.00%

print('percent: {:.0f}%'.format(10/50*100))

percent: 25%

特别说明

方式二相对于方式一,把%提到{}外,但计算值的时候必须乘以100

#小智的智商从去年的100分提升到今年的132分,请计算小智智商提升的百分比,并用字符串格式化显示出“xx.x%”的形式,保留一位小数

lastYearIQ = 100

thisYearIQ = 132

growthRateIQ = (thisYearIQ-lastYearIQ)/lastYearIQ

print('小智智商今年比去年提高了%.1f%%'%(growthRateIQ*100))

#输出:小智智商今年比去年提高了32.0%