textwrap——格式化文本段落
作用:通過調整換行符在段落中出現的位置來格式化文本。? ? ? ? ?Python 版本:2.5 及以后版本? ? ? ? ?需要美觀打印時,可以用 textwrap 模塊來格式化要輸出的文本。這個模塊允許通過編程提供類似段落自動換行或填充特性等功能。 示例數據
# textwrap_example.py
sample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired.? It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''
填充段落? ? ? ? ?fill() 函數取文本作為輸入,生成格式化的文本作為輸出。
import textwrap
from textwrap_example import sample_text
print 'No dedent:\n'
print textwrap.fill(sample_text, width=50)
去除現有縮進? ? ? ? ?在前面的例子中,輸出里混合嵌入了制表符和額外的空格,所以格式不太美觀。從示例文本刪除所有行中都有的空白符前綴可以生成更好的結果,從而能直接使用 Python 代碼中的 docstring 或嵌入的多行字符串,同時自動去除代碼的格式化。示例字符串人為地引入了一級縮進,以便展示這個特性。
import textwrap
from textwrap_example import sample_text
dedeted_text = textwrap.dedent(sample_text)
print 'Dedented:'
print dedented_text
由于 dedent(去除縮進)與 indent(縮進)正好相反,因此這里的結果是得到一個文本塊,而且刪除了各行最前面都有的空白符。如果某一行比其他行縮進更多,則會有一些空白符未刪除。? ? ? ? ?以下輸入:? Line one.? ? Line two.? Line three.? ? ? ? ?會變成: Line one.? ?Line two. Line three. 結合 dedent 和 fill? ? ? ? ?接下來,可以把去除縮進的文本傳入 fill(),并提供一組不同的 width 值。
import textwrap
from textwrap_example import sample_text
dedeted_text = textwrap.dedent(sample_text).strip()
for width in [ 45, 70 ]:
print '%d Columns:\n' % width
print textwrap.fill(dedented_text, width=width)
這會生成指定寬度的輸出。 懸掛縮進? ? ? ? ?不僅輸出的寬度可以設置,還可以單獨控制第一行的縮進,以區別后面各行。
import textwrap
from textwrap_example import sample_text
dedeted_text = textwrap.dedent(sample_text).strip()
print textwrap.fill(dedented_text,
initial_indent='',
subsequent_indent=' ' * 4,
width=50,
)
這樣會生成一種懸掛縮進,即第一行的縮進小于其他行的縮進。
縮進值還可以包含非空白字符。例如,懸掛縮進可以加前綴 * 來生成項目符號。