1. 程式人生 > >python中format用法

python中format用法

format是python2.6新增的一個格式化字串的方法,相對於老版的%格式方法,它有很多優點。

1.不需要理會資料型別的問題,在%方法中%s只能替代字串型別

2.單個引數可以多次輸出,引數順序可以不相同

3.填充方式十分靈活,對齊方式十分強大

4.官方推薦用的方式,%方式將會在後面的版本被淘汰

format的一個例子

1print'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.通過位置來填充字串

1 2 3 print'hello {0} i am {1}'.format('Kevin','Tom')# hello Kevin i am Tom print'hello {} i am {}'.format('Kevin','Tom')# hello Kevin i am Tom print'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來填充

1print'hello {name1}  i am {name2}'.format(name1='Kevin',name2='Tom')# hello Kevin i am Tom

3.通過下標填充

1 2 3 names=['Kevin','Tom'] print'hello {names[0]}  i am {names[1]}'.format(names=names)# hello Kevin i am Tom print'hello {0[0]}  i am {0[1]}'.format(names)# hello Kevin i am Tom

4.通過字典的key

12names={'name':'Kevin','name2':'Tom'}print'hello {names[name]}  i am {names[name2]}'.format(names=names)# hello Kevin i am Tom

注意訪問字典的key,不用引號的

5.通過物件的屬性

1 2 3 4 5 classNames(): name1='Kevin' name2='Tom' print