最多見的是按照位置進行format,日常用在參數的順序不太可能更改,而且須要用到的format比較少狀況。數據結構
按照位置進行format的缺點是:元素沒有用像名稱之類的具備描述性的東西來表示,因此這種 format 只適用於格式化相對較少的元素的狀況。ide
''' format字符串 ''' # 舊樣式 '%s %s' % ('one', 'two') # one two # 新樣式 '{} {}'.format('one', 'two') # one two Output ''' format數字''' # 舊樣式 '%d %d' % (1, 2) # 1 2 # 新樣式 '{} {}'.format(1, 2) # 1 2 Output ''' 還有一種新的format格式,能夠給佔位符一個顯式的位置索引。(在Python2.6中甚至是強制的) 這樣能夠在不更改參數的狀況下從新排列顯示順序。不過這個format不能用於舊版本。 ''' # 新樣式 '{1} {0}'.format('one', 'two') # two one
默認狀況下,新樣式的簡單格式化程序是調用對象的__format__()方法。若是隻想呈現str(…)或repr(…)的輸出,可使用 !s 或 !r 進行標識。spa
在%樣式中,一般使用%s表示字符串,%r表示repr(…)轉換。code
class Data(object): def __str__(self): return 'str' def __repr__(self): return 'repr'
# 舊樣式 '%s %r' % (Data(), Data()) # str repr # 新樣式 '{0!s} {0!r}'.format(Data()) # str repr
Python 3 中存在一個使用repr(…)輸出但使用ascii(…)的附加轉換標誌。orm
class Data(object): def __repr__(self): return 'räpr'
# 舊樣式 '%r %a' % (Data(), Data()) # räpr r\xe4pr # 新樣式 '{0!r} {0!a}'.format(Data()) # räpr r\xe4pr
默認狀況下,值的格式設置爲只佔用表示內容所需的字符數。可是,也能夠定義一個值所需填充到的一個特定的長度。 對象
不過,新樣式和舊樣式格式的默認對齊方式不一樣。舊樣式默認爲右對齊,而新樣式默認爲左對齊。blog
'''右對齊''' # 舊樣式 '%10s' % ('test',) # test # 新樣式 '{:>10}'.format('test') # test Output '''左對齊''' # 舊樣式 '%-10s' % ('test',) # test # 新樣式 '{:10}'.format('test') # test
另外,新樣式format比起舊樣式,多了可使用指定字符填充、居中填充等功能索引
# 使用指定字符填充 '{:_<10}'.format('test') # test______ # 居中填充 '{:_^10}'.format('test') # ___test___ # 當使用居中填充時,若是字符串長度致使填充字符兩端長度不一樣,則多的字符將放置在右側: '{:_^6}'.format('zip')# _zip__
與填充相反,也能夠將過長的字符串截斷爲特定數量的字符。ip
# 舊樣式 '%.5s' % ('xylophone') # xylop # 新樣式 '{:.5}'.format('xylophone') # xylop
# 舊樣式 '%-10.5s' % ('xylophone') # xylop # 新樣式 '{:_<10.5}'.format('xylophone') # xylop_____
'''整型''' # 舊樣式 '%d' % (42) # 42 # 新樣式 '{:d}'.format(42) # 42 Output '''浮點型''' # 舊樣式 '%f' % (3.141592653589793) # 3.141593 # 新樣式 '{:f}'.format(3.141592653589793) # 3.141593
# 舊樣式 '%4d' % (42,) # 42 # 新樣式 '{:4d}'.format(42) # 42 # 一樣相似於截斷字符串,浮點數的精度限制小數點後的位置數。 # 對於浮點,填充值表示完整輸出的長度。 #在下面的示例中,咱們但願輸出至少有6個字符,小數點後有2個字符。 # 舊樣式 '%06.2f' % (3.141592653589793,) # 003.14 # 新樣式 '{:06.2f}'.format(3.141592653589793) # 003.14 Output # 對於提供精度的整數值來講,沒有多大意義,實際上在新樣式中是禁止的(它將致使valueerror)。 # 舊樣式 '%04d' % (42,) # 0042 # 新樣式 '{:04d}'.format(42) # 0042
默認狀況下,只有負數的前綴有符號,不過咱們也能夠把正數的加上。ci
# 舊樣式 '%+d' % (42) # +42 # 新樣式 '{:+d}'.format(42) # +42 '''使用空格字符表示負數應以減號做爲前綴,正數應使用前導空格''' # 舊樣式 '% d' % ((- 23)) # -23 '% d' % (42) # 42 # 新樣式 '{: d}'.format((- 23)) # -23 '{: d}'.format(42) # 42 '''新樣式格式還能夠控制符號相對於填充的位置。此操做不能用於舊樣式格式''' # 新樣式 '{:=5d}'.format((- 23)) # - 23 '{:=+5d}'.format(23) # + 23
佔位符支持命名,這樣就能夠參數的傳遞就能夠多樣化,既能夠是字典的形式也能夠是鍵值對的形式
# 傳遞的參數 data = {'first': 'hello', 'last': 'world!'} # 舊樣式 '%(first)s %(last)s' % data # hello world! # 新樣式 '{first} {last}'.format(**data) # hello world! # 新版本 '{first} {last}'.format(first='hello', last='world!') # hello world!
此操做不能用於舊樣式格式。
新的樣式格式容許在訪問嵌套數據結構時具備更大的靈活性。它支持訪問支持相似「getitem」的容器,例如字典和列表:
# 傳遞的參數 person = {'first': 'Jean-Luc', 'last': 'Picard'} # 新樣式 '{p[first]} {p[last]}'.format(p=person) # Jean-Luc Picard # 傳遞的參數 data = [4, 8, 15, 16, 23, 42] # 新樣式 '{d[4]} {d[5]}'.format(d=data) # 23 42 '''經過getAttr()訪問對象上的屬性''' class Plant(object): type = 'tree' # 新樣式 '{p.type}'.format(p=Plant()) # tree '''以上兩種類型能夠自由混合和任意嵌套''' class Plant(object): type = 'tree' kinds = [{'name': 'oak'}, {'name': 'maple'}] # 新樣式 '{p.type}: {p.kinds[0][name]}'.format(p=Plant()) # tree: oak
此操做不能用於舊樣式格式。
新樣式格式還容許對象控制本身的渲染。例如,容許之內聯方式格式化日期時間對象:
from datetime import datetime # 新樣式 '{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5)) # 2001-02-03 04:05
新樣式format容許使用參數化動態指定格式的全部組件。參數化格式是大括號中的嵌套表達式,能夠出如今冒號後面的父格式中的任何位置。
舊樣式的格式也支持一些參數化,但更爲有限。也就是說,它只容許對輸出的寬度和精度進行參數化。
'''對齊和長度參數化 ''' # 不支持舊樣式 # 新樣式 '{:{align}{width}}'.format('test', align='^', width='10') # test '''精度參數化''' # 舊樣式 '%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182) # Gib = 2.718 # 新樣式 '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3) # Gib = 2.718 '''長度和精度參數化''' # 舊樣式 '%*.*f' % (5, 2, 2.7182) # 2.72 # 新樣式 '{:{width}.{prec}f}'.format(2.7182, width=5, prec=2) # 2.72 '''嵌套format可用於替換format的任何部分,所以上面的精度示例可重寫爲''' # 不支持舊樣式 # 新樣式 '{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3') # Gib = 2.72 '''日期時間的組成部分能夠單獨設置''' # 不支持舊樣式 from datetime import datetime dt = datetime(2001, 2, 3, 4, 5) # 新樣式 '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M') # 2001-02-03 04:05 '''嵌套formats能夠是位置參數。位置取決於大括號的順序''' # 不支持舊樣式 # 新樣式 '{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3) # +2.72 '''關鍵字參數能夠添加到組合中''' # 不支持舊樣式 # 新樣式 '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+') # +2.72
此操做不能用於舊樣式格式。
datetime示例經過使用__format__()方法工做。經過重寫此方法,能夠在本身的對象中定義自定義格式處理。就能夠徹底控制所使用的格式語法。
class HAL9000(object): def __format__(self, format): if (format == 'open-the-pod-bay-doors'): return "I'm afraid I can't do that." return 'HAL 9000' # 新樣式 '{:open-the-pod-bay-doors}'.format(HAL9000()) # I'm afraid I can't do that.