本库主要提供一些转换函数来实现文本的格式化,它的功能与类TextWrapper是一样的,不过在处理比较小的文本时是合适的,如果需要处理大量文本还是使用类TextWrapper效率更高,更加合适。
textwrap.wrap(text, width=70, **kwargs)
格式化一段文本字符串,按指定的width宽度进行自动动换行,结束行没有新的换行。
返回一个分行保存的列表。
参数text是输入进行格式化的文本。
参数width是格式化后每行的宽度。
参数kwargs是关键字参数,用来指定特定格式化功能。
例子:
#python 3.4.3 import textwrap text = 'this for test!' format = textwrap.wrap(text, 10) for line in format: print(line) text = '''<I am afraid> You say that you love the rain, but you open your umbrella when it rains. You say that you love the sun, but you find a shadow spot when the sun shines. You say that you love the wind, but you close your windows when wind blows. This is why I am afraid, when you say that you love me too.''' format = textwrap.wrap(text) for line in format: print(line) text = '''你说你爱雨,但当细雨飘洒时你却撑开了伞; 你说你爱太阳,但当日当空时你却往荫处躲; 你说你爱风,但当它轻拂时你却紧紧地关上了自己的窗子; 所以当你说你爱我,我却会为此而烦忧。''' format = textwrap.wrap(text, 20) for line in format: print(line)
结果输出如下:
this for
test!
<I am afraid> You say that you love the rain, but you open your
umbrella when it rains. You say that you love the sun, but you find a
shadow spot when the sun shines. You say that you love the wind, but
you close your windows when wind blows. This is why I am afraid, when
you say that you love me too.
你说你爱雨,但当细雨飘洒时你却撑开了伞;
你说你爱太阳,但当日当空时你却往荫处躲;
你说你爱风,但当它轻拂时你却紧紧地关上了
自己的窗子;
所以当你说你爱我,我却会为此而烦忧。
从这里看到上面的格式后的文本是按不同的宽度来排列,第一个是按10个字符宽度来排版,第二个是按默认值70个来排版,第三个是按20个字符来排版。
蔡军生 微信号:shenzhencai 深圳