python中format主要是用來格式化字符串的。
format用法相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,
并且使用大括號‘{}’作為特殊字符代替‘%’
使用方法由兩種:b.format(a)和format(a,b)。
1、基本用法
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
1>>>print('{}{}'.format('hello','world'))#不帶字段
2helloworld
3>>>print('{0}{1}'.format('hello','world'))#帶數字編號
4helloworld
5>>>print('{0}{1}{0}'.format('hello','world'))#打亂順序
6helloworldhello
7>>>print('{1}{1}{0}'.format('hello','world'))
2、進階用法
(1)<(默認)左對齊、>右對齊、^中間對齊、=(只用于數字)在小數點后進行補齊
(2)取位數“{:4s}”、"{:.2f}"等
1>>>print('{}and{}'.format('hello','world'))#默認左對齊
2helloandworld
3>>>print('{:10s}and{:>10s}'.format('hello','world'))#取10位左對齊,取10位右對齊
4helloandworld
5>>>print('{:^10s}and{:^10s}'.format('hello','world'))#取10位中間對齊
6helloandworld
7>>>print('{}is{:.2f}'.format(1.123,1.123))#取2位小數
81.123is1.12
9>>>print('{0}is{0:>10.2f}'.format(1.123))#取2位小數,右對齊,取10位
101.123is1.12
以上內容為大家介紹了python培訓之format是什么,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。