標籤:寬度 文章 報錯 使用 置中 參數順序 char attribute alt
文法
它通過{}和:來代替%。
“映射”樣本
通過位置
字串的format函數可以接受不限個參數,位置可以不按順序,可以不用或者用多次,不過2.6不可為空{},2.7才可以。
通過關鍵字
通過對象屬性
通過下標
有了這些便捷的“映射”方式,我們就有了偷懶利器。基本的python知識告訴我們,list和tuple可以通過“打散”成普通參數給函數,而dict可以打散成關鍵字參數給函數(通過和*)。所以可以輕鬆的傳個list/tuple/dict給format函數。非常靈活。
格式限定符
它有著豐富的的“格式限定符”(文法是{}中帶:號),比如:
填充與對齊
填充常跟對齊一起使用
^、<、>分別是置中、靠左對齊、靠右對齊,後面頻寬度
:號後面帶填充的字元,只能是一個字元,不指定的話預設是用空格填充
比如
精度與類型f
精度常跟類型f一起使用
其中.2表示長度為2的精度,f表示float類型。
其他類型
主要就是進位了,b、d、o、x分別是二進位、十進位、八進位、十六進位。
用,號還能用來做金額的千位分隔字元。
format是python2.6新增的一個格式化字串的方法,相對於老版的%格式方法,它有很多優點。
1.不需要理會資料類型的問題,在%方法中%s只能替代字串類型
2.單個參數可以多次輸出,參數順序可以不相同
3.填充方式十分靈活,對齊十分強大
4.官方推薦用的方式,%方式將會在後面的版本被淘汰
format的一個例子
| 1 |
print ‘hello {0}‘.format(‘world‘) |
會輸出hello world
format的格式
replacement_field ::= “{” [field_name] [“!” conversion] [“:” format_spec] “}”field_name ::= arg_name (“.” attribute_name | “[” element_index “]”)*arg_name ::= [identifier | integer]attribute_name ::= identifierelement_index ::= integer | index_stringindex_string ::= <any source character except “]”> +conversion ::= “r” | “s” | “a”format_spec ::= <described in the next section>format_spec 的格式
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]fill ::= <any character>align ::= ”<” | “>” | “=” | “^”sign ::= ”+” | “-” | ” “width ::= integerprecision ::= integertype ::= ”b” | “c” | “d” | “e” | “E” | “f” | “F” | “g” | “G” | “n” | “o” | “s” | “x” | “X” | “%”
應用:
一 填充
1.通過位置來填充字串
| 123 |
print ‘hello {0} i am {1}‘.format(‘Kevin‘,‘Tom‘) # hello Kevin i am Tomprint ‘hello {} i am {}‘.format(‘Kevin‘,‘Tom‘) # hello Kevin i am Tomprint ‘hello {0} i am {1} . my name is {0}‘.format(‘Kevin‘,‘Tom‘) # hello Kevin i am Tom . my name is Kevin |
foramt會把參數按位置順序來填充到字串中,第一個參數是0,然後1 ……
也可以不輸入數字,這樣也會按順序來填充
同一個參數可以填充多次,這個是format比%先進的地方
2.通過key來填充
| 1 |
print ‘hello {name1} i am {name2}‘.format(name1=‘Kevin‘,name2=‘Tom‘) # hello Kevin i am Tom |
3.通過下標填充
| 123 |
names=[‘Kevin‘,‘Tom‘]print ‘hello {names[0]} i am {names[1]}‘.format(names=names) # hello Kevin i am Tomprint ‘hello {0[0]} i am {0[1]}‘.format(names) # hello Kevin i am Tom |
4.通過字典的key
| 12 |
names={‘name‘:‘Kevin‘,‘name2‘:‘Tom‘}print ‘hello {names[name]} i am {names[name2]}‘.format(names=names) # hello Kevin i am Tom |
注意訪問字典的key,不用引號的
5.通過對象的屬性
| 12345 |
class Names(): name1=‘Kevin‘ name2=‘Tom‘ print ‘hello {names.name1} i am {names.name2}‘.format(names=Names) # hello Kevin i am Tom |
6.使用魔法參數
| 123 |
args=[‘lu‘]kwargs = {‘name1‘: ‘Kevin‘, ‘name2‘: ‘Tom‘}print ‘hello {name1} {} i am {name2}‘.format(*args, **kwargs) # hello Kevin i am Tom |
二 格式轉換
b、d、o、x分別是二進位、十進位、八進位、十六進位。
| 數字 |
格式 |
輸出 |
描述 |
| 3.1415926 |
{:.2f} |
3.14 |
保留小數點後兩位 |
| 3.1415926 |
{:+.2f} |
3.14 |
帶符號保留小數點後兩位 |
| -1 |
{:+.2f} |
-1 |
帶符號保留小數點後兩位 |
| 2.71828 |
{:.0f} |
3 |
不帶小數 |
| 1000000 |
{:,} |
1,000,000 |
以逗號分隔的數字格式 |
| 0.25 |
{:.2%} |
25.00% |
百分比格式 |
| 1000000000 |
{:.2e} |
1.00E+09 |
指數記法 |
| 25 |
{0:b} |
11001 |
轉換成二進位 |
| 25 |
{0:d} |
25 |
轉換成十進位 |
| 25 |
{0:o} |
31 |
轉換成八進位 |
| 25 |
{0:x} |
19 |
轉換成十六進位 |
三 對齊與填充
| 數字 |
格式 |
輸出 |
描述 |
| 5 |
{:0>2} |
05 |
數字補零 (填充左邊, 寬度為2) |
| 5 |
{:x<4} |
5xxx |
數字補x (填充右邊, 寬度為4) |
| 10 |
{:x^4} |
x10x |
數字補x (填充右邊, 寬度為4) |
| 13 |
{:10} |
13 |
靠右對齊 (預設, 寬度為10) |
| 13 |
{:<10} |
13 |
靠左對齊 (寬度為10) |
| 13 |
{:^10} |
13 |
中間對齊 (寬度為10) |
四 其他
1.轉義{和}符號
| 1 |
print ‘{{ hello {0} }}‘.format(‘Kevin‘) |
跟%中%%轉義%一樣,formate中用兩個大括弧來轉義
2.format作為函數
| 12 |
f = ‘hello {0} i am {1}‘.format print f(‘Kevin‘,‘Tom‘) |
3.格式化datetime
| 12 |
now=datetime.now()print ‘{:%Y-%m-%d %X}‘.format(now) |
4.{}內嵌{}
| 1 |
print ‘hello {0:>{1}} ‘.format(‘Kevin‘,50) |
5.歎號的用法
!後面可以加s r a 分別對應str() repr() ascii()
作用是在填充前先用對應的函數來處理參數
| 12 |
print "{!s}".format(‘2‘) # 2print "{!r}".format(‘2‘) # ‘2‘ |
差別就是repr帶有引號,str()是面向使用者的,目的是可讀性,repr()是面向Python解析器的,傳回值表示在python內部的含義
ascii()一直報錯,可能這個是3.0才有的函數
參考:https://docs.python.org/3/library/string.html#grammar-token-conversion
Python中format的用法