python模組學習- textwrap 文字包裝和填充
程式碼例項:
sample_text = '''
The textwrap module can beused to format text for output in
situations wherepretty-printing is desired. It offers
programmatic functionalitysimilar to the paragraph wrapping
or filling features found inmany text editors.
'''
段落填充:
import textwrap from textwrap_exampleimport sample_text print 'Nodedent:\n' printtextwrap.fill(sample_text, width=50)
執行結果:
# pythontextwrap_fill.py
No dedent:
The textwrap module can be used to format
text for outputin situations where pretty-
printing is desired. It offers programmatic
functionalitysimilar to the paragraph wrapping
or fillingfeatures found in many text editors.
結果為左對齊,第一行有縮排。行中的空格繼續保留。
移除縮排:
import textwrap fromtextwrap_example import sample_text dedented_text = textwrap.dedent(sample_text) print 'Dedented:' printdedented_text
執行結果:
# pythontextwrap_dedent.py
Dedented:
The textwrapmodule can be used to format text for output in
situations wherepretty-printing is desired. It offers
programmaticfunctionality similar to the paragraph wrapping
or fillingfeatures found in many text editors.
這樣第一行就不會縮排。
結合移除縮排和填充:
import textwrap fromtextwrap_example import sample_text dedented_text =textwrap.dedent(sample_text).strip() for width in [ 45,70 ]: print '%d Columns:\n' % width print textwrap.fill(dedented_text,width=width) print
執行結果:
# pythontextwrap_fill_width.py
45 Columns:
The textwrapmodule can be used to format
text for output insituations where pretty-
printing isdesired. It offers programmatic
functionalitysimilar to the paragraph
wrapping orfilling features found in many
text editors.
70 Columns:
The textwrapmodule can be used to format text for output in
situations wherepretty-printing is desired. It offersprogrammatic
functionality similarto the paragraph wrapping or filling features
found in many texteditors.
懸掛縮排:懸掛縮排第一行的縮排小於其他行的縮排。
import textwrap fromtextwrap_example import sample_text dedented_text =textwrap.dedent(sample_text).strip() printtextwrap.fill(dedented_text, initial_indent='', subsequent_indent=' ' * 4, width=50, ) 執行結果: # pythontextwrap_hanging_indent.py The textwrapmodule can be used to format text for output in situations where pretty-printingis desired. It offers programmatic functionality similar to the paragraph wrapping orfilling features found in many text editors.
其中的’’*4還可以使用其他字元代替。
TextWrap提供函式wrap()和fill(), 以及TextWrapper類,工具函式dedent(). 通常包裝或者填充一兩個字串使用wrap()和fill()。其他情況使用TextWrapper更高效。
textwrap.wrap(text[,width[, ...]])
包裝單個段落(text為輸入,系字串),每行最長寬度width。返回輸出行的列表,最後行無換行符。Width預設70。
textwrap.fill(text[,width[, ...]])
包裝單段文字,並返回包含包裹段落的字串。實際上是"\n".join(wrap(text,...))的縮寫。wrap() and fill()建立TextWrapper例項,並呼叫一個方法。這些例項不被重用,所以包裝/填充很多文字字串要構造自己的TextWrapper物件更有效。TextWrapper.break_long_words設定是否拆長單詞。
textwrap.dedent(text)
反縮排去除每行行首的空白。這方便顯示三引號中的內容而不修改其原始碼中的縮排。