format用法:
python的格式化輸出常用的有兩種方式,一種是%,另外一種是{}.format,但是format的功能是遠遠強於%的,下面具體介紹這種用法。
基本用法
(1)不帶編號,即“{}”
(2)帶數字編號,可調換順序,即“{1}”、“{2}”
(3)帶關鍵字,即“{name}”、“{age}”
>>> print('{} {}'.format('hello','world')) # 不帶字段
hello world
>>> print('{0} {1}'.format('hello','world')) # 帶數字編號
hello world
>>> print('{0} {1} {0}'.format('hello','world')) # 打亂順序
hello world hello
>>> print('{1} {1} {0}'.format('hello','world'))
world world hello
>>> print('{name} {age} {name}'.format(name='wangjunjie',age='24')) # 帶關鍵字
wangjunjie 24 wangjunjie
進階用法
(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用於數字)在小數點後進行補齊
(2)取位數“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('hello','world')) # 默認左對齊
hello and world
>>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左對齊,取10位右對齊
hello and world
>>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中間對齊
hello and world
>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小數
1.123 is 1.12
>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小數,右對齊,取10位
1.123 is 1.12