Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強了字符串格式化的功能。
1.使用位置參數(shù)
>>> "{} love {}".format("boluo","chenchen")
'boluo love chenchen'
>>> "{1} love {0}".format("chenchen","boluo")
'boluo love chenchen'
>>> "{1} love {0} {1}".format("chenchen","boluo")
'boluo love chenchen boluo'
2.使用關(guān)鍵字參數(shù)
關(guān)鍵字參數(shù)值要對得上,另外可以通過字典和列表索引設(shè)置參數(shù)
>>> "{name1} love {name2}".format(name1="boluo",name2="chenchen")#關(guān)鍵字參數(shù)
'boluo love chenchen'
>>> "{0} love {name2}".format("boluo",name2="chenchen")#位置參數(shù)加關(guān)鍵字參數(shù)
'boluo love chenchen'
>>> site={"name1":"boluo","name2":"chenchen"}#使用字典設(shè)置參數(shù)
>>> "{name1} love {name2}".format(**site)
'boluo love chenchen'
3.傳入對象
4.格式化符號
4.1對數(shù)字格式化

image.png
b、d、o、x 分別是二進制、十進制、八進制、十六進制。
>>> "{0:.1f}{1}".format(2.3333,"b")#保留小數(shù)點后1位小數(shù)
'2.3b'
4.2 %字符串格式化

搜狗截圖20年04月02日2220_4.png
>>> "%c" % 100#格式化字符及ASCII碼
'd'
>>> "%d %d %d" % (12.3,235.35555,12)#格式化為整數(shù)
'12 235 12'
4.3格式化操作符輔助命令

搜狗截圖20年04月03日1526_5.png
>>> "%5.1f" % 27.222
' 27.2'
>>> "%-5.1f" % 27.222
'27.2 '
>>> "%+5.1f" % 27.222
'+27.2'
4.4字符串轉(zhuǎn)義字符

搜狗截圖20年04月03日1532_6.png