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

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.

此时已经消除了首行的缩进了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值