新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:pythonformat是什么
Python中FORMAT主要是用來(lái)格式化字符串的。

format用法相對(duì)基本格式化輸出采用‘%’的方法,format()功能更強(qiáng)大,該函數(shù)把字符串當(dāng)成一個(gè)模板,通過(guò)傳入的參數(shù)進(jìn)行格式化,
并且使用大括號(hào)‘{}’作為特殊字符代替‘%’
使用方法由兩種: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'))
2、進(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.12
python學(xué)習(xí)網(wǎng),大量的免費(fèi)python學(xué)習(xí)視頻,歡迎在線學(xué)習(xí)!
分享名稱:創(chuàng)新互聯(lián)Python教程:pythonformat是什么
標(biāo)題鏈接:http://www.dlmjj.cn/article/dpgjcio.html


咨詢
建站咨詢
