上一篇文章: Python實用技法第31篇:文本過濾和清理
下一篇文章: Python實用技法第33篇:字符串鏈接及合併
咱們須要以某種對齊方式將文本作格式化處理。html
對於基本的字符串對齊要求,能夠使用字符串的ljust()、rjust()和center()方法。示例以下:python
>>> text = 'Hello World' >>> text.ljust(20) 'Hello World ' >>> text.rjust(20) ' Hello World' >>> text.center(20) ' Hello World ' >>>
全部這些方法均可接受一個可選的填充字符。例如:segmentfault
>>> text.rjust(20,'=') '=========Hello World' >>> text.center(20,'*') '****Hello World*****' >>>
format()函數也能夠用來輕鬆完成對齊的任務。須要作的就是合理利用'<'、'>',或'^'字符以及一個指望的寬度值[2]。例如:函數
>>> format(text, '>20') ' Hello World' >>> format(text, '<20') 'Hello World ' >>> format(text, '^20') ' Hello World ' >>>
若是想包含空格以外的填充字符,能夠在對齊字符以前指定:code
>>> format(text, '=>20s') '=========Hello World' >>> format(text, '*^20s') '****Hello World*****' >>>
當格式化多個值時,這些格式化代碼也能夠用在format()方法中。例如:orm
>>> '{:>10s} {:>10s}'.format('Hello', 'World') ' Hello World' >>>
format()的好處之一是它並非特定於字符串的。它能做用於任何值,這使得它更加通用。例如,能夠對數字作格式化處理:htm
>>> x = 1.2345 >>> format(x, '>10') ' 1.2345' >>> format(x, '^10.2f') ' 1.23 '
在比較老的代碼中,一般會發現%操做符用來格式化文本。例如:對象
>>> '%-20s' % text 'Hello World ' >>> '%20s' % text ' Hello World'
可是在新的代碼中,咱們應該會更鐘情於使用format()函數或方法。format()比%操做符提供的功能要強大多了。此外,format()可做用於任意類型的對象,比字符串的ljust()、rjust()以及center()方法要更加通用。字符串
想了解format()函數的全部功能,請參考Python的在線手冊http://docs.python.org/3/libr... string. html#formatspec。get
上一篇文章: Python實用技法第31篇:文本過濾和清理
下一篇文章: Python實用技法第33篇:字符串鏈接及合併