【2】文件读写-8-2-文本包装和填充--textwrap

TextWrap提供函数wrap()和fill(), 以及TextWrapper类,工具函数dedent(). 通常包装或者填充一两个字符串使用wrap()和fill()。

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)

反缩进去除每行行首的空白。这方便显示三引号中的内容而不修改其源代码中的缩进。

实例文本:

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
print 'Nodedent:\n'
print textwrap.fill(sample_text, width=50)

执行结果:

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 fillingfeatues found in many text editors.

结果为左对齐,第一行有缩进。行中的空格继续保留。

例二:移除缩进

import textwrap
dedented_text = textwrap.dedent(sample_text)
print 'Dedented:'
print dedented_text

执行结果:

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
dedented_text =textwrap.dedent(sample_text).strip()
for width in [45,70]:
  print '%d Columns:\n' % width
  print textwrap.fill(dedented_text,width=width)

执行结果:

45 Columns:

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.
70 Columns:

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
 dedented_text =textwrap.dedent(sample_text).strip()
 print textwrap.fill(dedented_text,initial_indent='',subsequent_indent=' ' * 4,width=50,)

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.

参考资料:

http://www.2cto.com/kf/201305/210490.html

http://www.cnblogs.com/hongten/p/python_textwrap.html

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn