用法:
它通過(guò){}和:來(lái)代替?zhèn)鹘y(tǒng)%方式
1、使用位置參數(shù)
要點(diǎn):從以下例子可以看出位置參數(shù)不受順序約束厌漂,且可以為{},只要format里有相對(duì)應(yīng)的參數(shù)值即可,參數(shù)索引從0開(kāi)卫枝,傳入位置參數(shù)列表可用*列表
li = ['hoho',18]
'my name is {} ,age {}'.format('hoho',18)
# 'my name is hoho ,age 18'
'my name is {1} ,age {0}'.format(10,'hoho')
# 'my name is hoho ,age 10'
'my name is {1} ,age {0} {1}'.format(10,'hoho')
# 'my name is hoho ,age 10 hoho'
'my name is {} ,age {}'.format(*li)
# 'my name is hoho ,age 18'
2框舔、使用關(guān)鍵字參數(shù)
要點(diǎn):關(guān)鍵字參數(shù)值要對(duì)得上,可用字典當(dāng)關(guān)鍵字參數(shù)傳入值,字典前加**即可
hash = {'name':'hoho','age':18}
'my name is {name},age is {age}'.format(name='hoho',age=19)
'my name is hoho,age is 19'
'my name is {name},age is {age}'.format(**hash)
'my name is hoho,age is 18'
3透葛、填充與格式化
:[填充字符][對(duì)齊方式 <^>][寬度]
'{0:*>10}'.format(10) ##右對(duì)齊 '********10'
'{0:*<10}'.format(10) ##左對(duì)齊 '10********'
'{0:*^10}'.format(10) ##居中對(duì)齊 '****10****'</pre>
4休傍、精度與進(jìn)制
>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10) #二進(jìn)制
'1010'
>>> '{0:o}'.format(10) #八進(jìn)制
'12'
>>> '{0:x}'.format(10) #16進(jìn)制
'a'
>>> '{:,}'.format(12369132698) #千分位格式化
'12,369,132,698'
5、使用索引
name is {0[0]} age is {0[1]}'.format(li) '
name is hoho age is 18</pre>
@2018-01-31 08:46:09-晴天-寫(xiě)日志的時(shí)候format存貨不夠用了占键。昔善。