天天看點

Python格式化函數 | format()

介紹Python中format()函數的主要用法

格式化字元串:

基本格式:<模闆字元串>.format(<逗号分隔的參數>)

現有 : nums = [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]

要求輸出nums中元素個數.最大值.最小值

Python格式化函數 | format()
nums = [1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
len_,max_,min_ = len(nums),max(nums),min(nums)

#1:字元串拼接
print('nums有'+str(len_)+'個元素,最大值'+str(max_)+',最小值'+str(min_))
#2: %轉義
print('nums有%d個元素,最大值%d,最小值%d' % (len_,max_,min_))
#3: format函數 : 接受不限個參數,位置可以不按順序
print('nums有{0}個元素,最大值{1},最小值{2}'.format(len_,max_,min_))

#通過字典設定參數
dict = {'len':len_,'max':max_,'min':min_}
print('nums有{len}個元素,最大值{max},最小值{min}'.format(**dict))
#通過清單索引設定參數
target = [len_, max_, min_]
print('nums有{0[0]}個元素,最大值{0[1]},最小值{0[2]}'.format(target))

'''以上代碼都能輸出  nums有10個元素,最大值9,最小值0,
   但相對來說format()更美觀省事,功能也更強大'''
           

格式化數字:

格式控制資訊:format()方法中<模闆字元串>的槽除了包括參數序号,還可以包括格式控制資訊。此時,槽的内部樣式如下: {<參數序号>: <格式控制标記>}

其中,**<格式控制标記>用來控制參數顯示時的格式,包括:<填充><對齊><寬度>,<.精度><類型>**6 個字段,這些字段都是可選的,可以組合使用。

Python格式化函數 | format()
1:保留小數點後2位 : {:.2f}
import math
PI = math.pi   #PI --> 3.141592653589793
val = -2018.1229
print('{0:.2f}  {1:.2f}'.format(PI,val))    
#輸出  3.14  -2018.12
           
2:帶符号保留小數點後兩位 : {:+.2f}
print('{0:+.2f}  {1:+.2f}'.format(PI,val))     
#輸出  +3.14  -2018.12
           
3:舍棄小數 : {:.0f}
print('{0:.0f}  {1:.0f}'.format(PI,val)) 
#輸出  3  -2018
           
4:千位分隔符–> {:,}
print('{0:,}'.format(10000000))
#輸出  10,000,000
           

5:設定寬度為6,左填充 --> {0:>6d}

寬度為6,右填充x --> {:x<6d}

print('{0:*>6d}  {1:x<6d}'.format(2018,1229))
#輸出  **2018  1229xx
           

6:百分比格式 --> {:.2%} ,

指數格式 : {:.2e}

print('{0:.2%}  {1:.2e}'.format(0.25,10000000))
#輸出  25.00%  1.00e+07
           
7:設定對齊 : <左對齊 >右對齊 ^居中
print('{0:*<10d}  {1:*<10d}'.format(2018,1229))  #2018******  1229******
print('{0:*^10d}  {1:*^10d}'.format(2018,1229))  #***2018***  ***1229***
print('{0:*>10d}  {1:*>10d}'.format(2018,1229))  #******2018  ******1229
           

8:進制轉換

{:d} --> 十進制,

{:b} --> 二進制,

{:#b} --> 帶字首二進制,

{o} --> 八進制,

{:#o} --> 帶字首八進制,

{:x} --> 十六進制

{:#x}–> 帶字首十六進制

{:#X} --> 帶字首大寫十六進制

#用bin()轉二進制會帶有字首0b,但format()不會
d2b = bin(255)
use_format = format(255,'b')
print(d2b +'      '+use_format)  #輸出: 0b11111111      11111111

print('{:d}'.format(255))    #255
print('{:b}'.format(255))    #11111111
print('{:#b}'.format(255))   #0b11111111
print('{:o}'.format(255))    #377
print('{:#o}'.format(255))   #0o377
print('{:x}'.format(255))    #ff
print('{:#x}'.format(255))   #0xff
print('{:#X}'.format(255))   #0XFF
           
Python格式化函數 | format()

關注微信公衆号,擷取更多資料