11. Python 標準函式庫概覽——第二部份¶
第二部分涵蓋更多支援專業程式設計所需要的進階模組。這些模組很少出現在小腳本中。
11.1. 輸出格式化 (Output Formatting)¶
reprlib 模組提供了一個 repr() 的版本,專門用來以簡短的形式顯示大型或深層的巢狀容器:
>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
pprint 模組能對內建和使用者自定的物件提供更複雜的列印控制,並且是以直譯器可讀的方式。當結果超過一行時,「漂亮的印表機」會加入換行和縮排,以更清楚地顯示資料結構:
>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
... 'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]
textwrap 模組能夠格式化文本的段落,以符合指定的螢幕寬度:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.
locale 模組能存取一個含有特定文化相關資料格式的資料庫。locale 模組的 format 函式有一個 grouping 屬性,可直接以群分隔符 (group separator) 將數字格式化:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv() # 取得慣例的對映
>>> x = 1234567.8
>>> locale.format_string("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
... conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
11.2. 模板化 (Templating)¶
string 模組包含一個多功能的 Template class,提供的簡化語法適合使用者進行編輯時使用。它容許使用者客製化自己的應用程式,但不必對原應用程式做出變更。
格式化方式是使用佔位符號名稱 (placeholder name),它是由 $ 加上合法的 Python 識別符(字母、數字和下底線)構成。使用大括號包覆佔位符號以允許在後面接上更多的字母和數字而無需插入空格。使用 $$ 將會跳脫為單一字元 $:
>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'
如果在 dictionary 或關鍵字引數中未提供某個佔位符號的值,那麼 substitute() method 將引發 KeyError。對於郵件合併 (mail-merge) 類型的應用程式,使用者提供的資料有可能是不完整的,此時使用 safe_substitute() method 會更適當——如果資料有缺少,它會保持佔位符號不變:
>>> t = Template('Return the $item to $owner.')
>>> d