textwrap——文本包裹和填充模块解析

        textwrap模块提供了两个函数wrap()和fill(),以及TextWrapper类,以及另外一个工具函数dedent()。

        wrap()以及fill()都可以用来格式化一大段文本,将指定文本限制在一定的屏幕宽度。例如
  1.  1 >>> import textwrap
     2 >>> doc = """The wrap() method is just like fill() except that it returns
     3 ... a list of strings instead of one big string with newlines to separate
     4 ... the wrapped lines."""
     5 ...
     6 >>> print textwrap.fill(doc, width=40)
     7 The wrap() method is just like fill()
     8 except that it returns a list of strings
     9 instead of one big string with newlines
    10 to separate the wrapped lines.
        wrap()和fill()的区别是,wrap()返回的是个列表,而fill()返回一个字符串。
        dedent()用来清除空白字符。例如
  1. 1 def test():
    2     # end first line with \ to avoid the empty line!
    3     s = '''\
    4     hello
    5       world
    6     '''
    7     print repr(s)          # prints '    hello\n      world\n    '
    8     print repr(dedent(s))  # prints 'hello\n  world\n'
        此外也可以使用TextWrapper类构造对象,例如:
  1. 1 wrapper =TextWrapper(initial_indent="* ")

 

posted @ 2015-10-09 19:14  楚狂人阿飞  阅读(412)  评论(0编辑  收藏  举报