Python如何輸出百分比
Python 輸出百分比的兩種方式
注: 在python3環(huán)境下測試。
方式1:直接使用參數(shù)格式化:{:.2%}
{:.2%}: 顯示小數(shù)點后2位
顯示小數(shù)點后2位:
>>> print(’percent: {:.2%}’.format(42/50))percent: 84.00%
不顯示小數(shù)位:{:.0%},即,將2改為0:
>>> print(’percent: {:.0%}’.format(42/50))percent: 84%
方式2:格式化為float,然后處理成%格式: {:.2f}%
與方式1的區(qū)別是:
(1) 需要對42/50乘以 100 。 (2) 方式2的%在{ }外邊,方式1的%在{ }里邊。
顯示小數(shù)點后2位:
>>> print(’percent: {:.2f}%’.format(42/50*100))percent: 84.00%
顯示小數(shù)點后1位:
>>> print(’percent: {:.1f}%’.format(42/50*100))percent: 84.0%
只顯示整數(shù)位:
>>> print(’percent: {:.0f}%’.format(42/50*100))percent: 84%
說明
{ } 的意思是對應(yīng)format()的一個參數(shù),按默認(rèn)順序?qū)?yīng),參數(shù)序號從0開始,{0}對應(yīng)format()的第一個參數(shù),{1}對應(yīng)第二個參數(shù)。例如:
默認(rèn)順序:
>>> print(’percent1: {:.2%}, percent2: {:.1%}’.format(42/50, 42/100))percent1: 84.00%, percent2: 42.0%
指定順序:
{1:.1%}對應(yīng)第2個參數(shù); {0:.1%}對應(yīng)第1個參數(shù)。
>>> print(’percent2: {1:.1%}, percent1: {0:.1%}’.format(42/50, 42/100))percent2: 42.0%, percent1: 84.0%
到此這篇關(guān)于Python 如何輸出百分比的文章就介紹到這了,更多相關(guān)Python 輸出百分比內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python 實現(xiàn)rolling和apply函數(shù)的向下取值操作2. CSS代碼檢查工具stylelint的使用方法詳解3. 淺談python多線程和多線程變量共享問題介紹4. Python如何批量獲取文件夾的大小并保存5. vue3?Error:Unknown?variable?dynamic?import:?../views/的解決方案6. python利用platform模塊獲取系統(tǒng)信息7. react axios 跨域訪問一個或多個域名問題8. Python的Tqdm模塊實現(xiàn)進(jìn)度條配置9. Python 多線程之threading 模塊的使用10. WML語言的基本情況
