format-字符串格式化

順序寫入:{}

a='{} ---- {} ----- {}'.format('abort','bank','cat')                  #abort ---- bank ----- cat

數字指定傳入的參數:{2}

a='{2} ---- {0} ----- {2}'.format('abort','bank','cat')             #cat ---- abort ----- cat

指定傳入的參數、長度:{2:5s}

a='{2:5s} ---- {2:5s} ----- {2:10s} ----'.format('abort','bank','cat')      #cat   ---- cat   ----- cat        ----

傳入元組:(*tuple_var)

b=('abort','bank','cat','def')
a='{} ---- {} ----- {}'.format(*b)

傳入元組2:(*tuple_var)

t=(111,444)
h='x:{0[0]}---y:{0[1]}'.format(t)                                        x:111---y:444

關鍵字參數:{key}

h='--- a={a}--- b={b}'.format(a=111,b=222,c=333)         #--- a=111--- b=222                                       x:111---y:444

傳入字典:(**dict_var)

d={'a':111,'b':222,'c':333}
h='--- a={a}--- b={b}'.format(**d)                                     #--- a=111--- b=222

傳入對象

c=22+33j
h='real:{0.real}----imag:{0.imag}'.format(c)                  #real:22.0----imag:33.0      
h='real:{a.real}----imag:{a.imag}'.format(a=c)              #real:22.0----imag:33.0      

左對齊,右對齊,居中

h='{:<30}'.format('left aligned')        
print(h) #'left aligned                  '
h='{:>30}'.format('right aligned')
print(h) #'                 right aligned'
h='{:^30}'.format('centered')
print(h)        #'           centered           '
h='{:*^30}'.format('centered')  # use '*' as a fill char:***********centered***********
print(h)

正數前用加號或空格填充

h='---{0:+f}----{0: f}---{0:f}---'.format(3.14, -3.14)            #---+3.140000---- 3.140000---3.140000---

其他進制:加#的區別

h="int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)                #int: 42;  hex: 2a;  oct: 52;  bin: 101010
print(h)                                
h="int: {0:#d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)        #int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010
print(h)

千分符:,

h='{:,}'.format(1234567890)                         #1,234,567,890

限制小數位:.

h='Correct answers: {:.3%}'.format(9/11)            #Correct answers: 81.818%
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章