新聞中心
FORMAT用法相對基本格式化輸出采用‘%’的方法,format()功能更強大,該函數(shù)把字符串當(dāng)成一個模板,通過傳入的參數(shù)進行格式化,并且使用大括號‘{}’作為特殊字符代替‘%’

舞鋼網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站設(shè)計等網(wǎng)站項目制作,到程序開發(fā),運營維護。成都創(chuàng)新互聯(lián)公司自2013年創(chuàng)立以來到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)公司。
使用方法由兩種:b.format(a)和format(a,b)。
1、基本用法
(1)不帶編號,即“{}”
(2)帶數(shù)字編號,可調(diào)換順序,即“{1}”、“{2}”
(3)帶關(guān)鍵字,即“{a}”、“{tom}”
1 >>> print('{} {}'.format('hello','world')) # 不帶字段
2 hello world
3 >>> print('{0} {1}'.format('hello','world')) # 帶數(shù)字編號
4 hello world
5 >>> print('{0} {1} {0}'.format('hello','world')) # 打亂順序
6 hello world hello
7 >>> print('{1} {1} {0}'.format('hello','world'))
8 world world hello
9 >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 帶關(guān)鍵字
10 world hello world2、進階用法
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用于數(shù)字)在小數(shù)點后進行補齊
(2)取位數(shù)“{:4s}”、"{:.2f}"等
1 >>> print('{} and {}'.format('hello','world')) # 默認左對齊
2 hello and world
3 >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左對齊,取10位右對齊
4 hello and world
5 >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中間對齊
6 hello and world
7 >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小數(shù)
8 1.123 is 1.12
9 >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小數(shù),右對齊,取10位
10 1.123 is 1.123、多個格式化
'b' - 二進制。將數(shù)字以2為基數(shù)進行輸出。
'c' - 字符。在打印之前將整數(shù)轉(zhuǎn)換成對應(yīng)的Unicode字符串。
'd' - 十進制整數(shù)。將數(shù)字以10為基數(shù)進行輸出。
'o' - 八進制。將數(shù)字以8為基數(shù)進行輸出。
'x' - 十六進制。將數(shù)字以16為基數(shù)進行輸出,9以上的位數(shù)用小寫字母。
'e' - 冪符號。用科學(xué)計數(shù)法打印數(shù)字。用'e'表示冪。
'g' - 一般格式。將數(shù)值以fixed-point格式輸出。當(dāng)數(shù)值特別大的時候,用冪形式打印。
'n' - 數(shù)字。當(dāng)值為整數(shù)時和'd'相同,值為浮點數(shù)時和'g'相同。不同的是它會根據(jù)區(qū)域設(shè)置插入數(shù)字分隔符。
'%' - 百分數(shù)。將數(shù)值乘以100然后以fixed-point('f')格式打印,值后面會有一個百分號。
1 >>> print('{0:b}'.format(3))
2 11
3 >>> print('{:c}'.format(20))
4
5 >>> print('{:d}'.format(20))
6 20
7 >>> print('{:o}'.format(20))
8 24
9 >>> print('{:x}'.format(20))
10 14
11 >>> print('{:e}'.format(20))
12 2.000000e+01
13 >>> print('{:g}'.format(20.1))
14 20.1
15 >>> print('{:f}'.format(20))
16 20.000000
17 >>> print('{:n}'.format(20))
18 20
19 >>> print('{:%}'.format(20))
20 2000.000000%
21 >>> 名稱欄目:創(chuàng)新互聯(lián)Python教程:python的format怎么用
URL鏈接:http://www.dlmjj.cn/article/cojgoep.html


咨詢
建站咨詢
