PyFormat字符串格式化實(shí)例
PyFormat 是記錄 Python 字符串格式化系統(tǒng)的實(shí)例的項(xiàng)目。python.org 的官方文檔中,包含了大量的關(guān)于格式化語(yǔ)法規(guī)范的信息,以及一些例子,但他們的文檔太理論和技術(shù)化了。這個(gè)項(xiàng)目把常用格式化的新老風(fēng)格直觀地展示出來(lái),提供了實(shí)際的例子。
如果沒(méi)有特別注明外,所有的例子使用 Python2.7,3.2,3.3,和3.4,而無(wú)需任何額外的庫(kù)或 monkey-patching。
基本的格式化:
Old
'%s %s' % ('one', 'two')
New
'{} {}'.format('one', 'two')
Output
one two
數(shù)值轉(zhuǎn)換:
Setup
class Data(object): def __str__(self): return 'str' def __repr__(self): return 'repr'
Old
'%s %r' % (Data(), Data())
New
'{0!s} {0!r}'.format(Data())
Output
str repr
填充和對(duì)齊字符串:
右對(duì)齊:
Old
'%10s' % ('test',)
New
'{:>10}'.format('test')
Output
test
長(zhǎng)字符串截位:
Old
'%.5s' % ('xylophone',)
New
'{:.5}'.format('xylophone')
Output
xylop
評(píng)論
圖片
表情
