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

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


咨詢
建站咨詢
