您的位置:首页 > 编程语言 > Python开发

python2.7中模块学习- textwrap 文本包装和填充

2016-07-08 17:02 363 查看
1.TextWrap提供函数wrap()和fill(),以及TextWrapper类,工具函数dedent().通常包装或者填充一两个字符串使用wrap()和fill()。其他情况使用TextWrapper更高效。

2.textwrap.wrap(text[,width[, …]]):包装单个段落(text为输入,系字符串),每行最长宽度width。返回输出行的列表,最后行无换行符。Width默认70。

3.textwrap.fill(text[,width[, …]]):包装单段文字,并返回包含包裹段落的字符串。实际上是”\n”.join(wrap(text,…))的缩写。wrap() andfill()创建TextWrapper实例,并调用一个方法。这些实例不被重用,所以包装/填充很多文本字符串要构造自己的TextWrapper对象更有TextWrapper.break_long_words设置是否拆长单词。

4.textwrap.dedent(text):反缩进去除每行行首的空白。这方便显示三引号中的内容而不修改其源代码中的缩进。

代码示例:(注意:在python2.7中没有from textwrap_example import sample_text 的用法,所以我们事先设定一个简单的text字符串)

text=”’ Object for wrapping/filling text. The public interface consists

of the wrap() and fill() methods; the other methods are just there for

subclasses to override in order to tweak the default behaviour.”’

(1)wrap的用法:

>>> import textwrap
>>> print textwrap.wrap(text,width=70)
[' Object for wrapping/filling text.  The public interface consists of', 'the wrap() and fill() methods; the other methods are just there for', 'subclasses to override in order to tweak the default behaviour.']
>>>


从结果看wrap把text分成等长的序列了。

(2)fill的用法:

text=''' Object for wrapping/filling text.The public
interfaceconsists of the wrap() and fill() methods; the
other methods arejust there for subclasses to override in
order to tweak the default behaviour.'''
import textwrap
print 'Nodedent:\n'
print textwrap.fill(text,width=50)


输出结果为:

Nodedent:

Object for wrapping/filling text.The public

interfaceconsists of the wrap() and fill()

methods; the other methods arejust there for

subclasses to override in order to tweak the

default behaviour.

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

(3)denent的用法:

import textwrap
text='''Object for wrapping/filling text.The public
interfaceconsists of the wrap() and fill() methods; the
other methods arejust there for subclasses to override in
order to tweak the default behaviour.'''
dedented_text = textwrap.dedent(text)
print 'Dedented:'
print dedented_text


输出结果为:

Dedented:

Object for wrapping/filling text.The public

interfaceconsists of the wrap() and fill() methods; the

other methods arejust there for subclasses to override in

order to tweak the default behaviour.

此时已经消除了首行的缩进了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息