python的format用法相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數(shù)把字符串當成一個模板,通過傳入的參數(shù)進行格式化,并且使用大括號‘{}’作為特殊字符代替‘%’
使用方法由兩種:b.format(a)和format(a,b)。
1、基本用法
(1)不帶編號,即“{}”
(2)帶數(shù)字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{a}”、“{tom}”
1>>>print('{}{}'.format('hello','world'))#不帶字段
2helloworld
3>>>print('{0}{1}'.format('hello','world'))#帶數(shù)字編號
4helloworld
5>>>print('{0}{1}{0}'.format('hello','world'))#打亂順序
6helloworldhello
7>>>print('{1}{1}{0}'.format('hello','world'))
8worldworldhello
9>>>print('{a}{tom}{a}'.format(tom='hello',a='world'))#帶關鍵字
10worldhelloworld
2、進階用法
(1)<(默認)左對齊、>右對齊、^中間對齊、=(只用于數(shù)字)在小數(shù)點后進行補齊
(2)取位數(shù)“{: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位小數(shù)
81.123is1.12
9>>>print('{0}is{0:>10.2f}'.format(1.123))#取2位小數(shù),右對齊,取10位
101.123is1.12
3、多個格式化
'b'-二進制。將數(shù)字以2為基數(shù)進行輸出。
'c'-字符。在打印之前將整數(shù)轉換成對應的Unicode字符串。
'd'-十進制整數(shù)。將數(shù)字以10為基數(shù)進行輸出。
'o'-八進制。將數(shù)字以8為基數(shù)進行輸出。
'x'-十六進制。將數(shù)字以16為基數(shù)進行輸出,9以上的位數(shù)用小寫字母。
'e'-冪符號。用科學計數(shù)法打印數(shù)字。用'e'表示冪。
'g'-一般格式。將數(shù)值以fixed-point格式輸出。當數(shù)值特別大的時候,用冪形式打印。
'n'-數(shù)字。當值為整數(shù)時和'd'相同,值為浮點數(shù)時和'g'相同。不同的是它會根據(jù)區(qū)域設置插入數(shù)字分隔符。
'%'-百分數(shù)。將數(shù)值乘以100然后以fixed-point('f')格式打印,值后面會有一個百分號。
1>>>print('{0:b}'.format(3))
211
3>>>print('{:c}'.format(20))
4
5>>>print('{:d}'.format(20))
620
7>>>print('{:o}'.format(20))
824
9>>>print('{:x}'.format(20))
1014
11>>>print('{:e}'.format(20))
122.000000e+01
13>>>print('{:g}'.format(20.1))
1420.1
15>>>print('{:f}'.format(20))
1620.000000
17>>>print('{:n}'.format(20))
1820
19>>>print('{:%}'.format(20))
202000.000000%
21>>>
以上內容為大家介紹了python培訓之format怎么用,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。