每日一“酷”之textwrap

介绍:需要美观打印时,可以使用textwrap模块来格式化要输出的文本,这个模块允许通过编程提高类似段落自动换行或填充特性等功能。

1 创建实例数据

1 sample_text = '''
2     I’m very happy and I like to make friends with others. 
3     I  also like singing but traveling is my favorite,   I have been to  many interesting places in China but I haven’t been to other  countries. 
4     What a pity!At school,    I study Chinese,math, English, history, politics  and so on. I like all of them. 
5     I often help my teacher take   care of my class and I think I am a good helper. 
6     I live  with my parents and we go home on time every day.
7     '''

创建 testwrap_example.py 文件 其中保存 sample_text 这段文本信息
2 填充段落

1 import textwrap
2 from testwrap_example import sample_text
3 print 'No dedent: 
'
4 print textwrap.fill(sample_text, width=50)

运行结果:

现在的状况是左对齐,只有第一行保留了缩进,其余各行前面的恐吓则嵌入到了段落中。

3、去除现有缩进

1 import textwrap
2 from testwrap_example import sample_text
3 dedented_text = textwrap.dedent(sample_text)
4 print 'Dedented: 
'
5 print dedented_text

运行结果:

由于“dedent(去除缩进)”与“indent(缩进)”正好相反,因此这里的结果是得到一个文本框,而且删除各行最前面的空白处。如果莫一行比其他行锁紧更多,曾辉有一些空白符未删除。即使:

执行前(!代表空格):

!aaa

!!!aaa

!bbb

执行后:

aaa

!!aaa

bbb

4、结合dedent 和 fill

现在讲去除缩进的文本传入到fill(),并提供一组不同的wideh值(改值控制显示的宽度) 

1 import textwrap
2 from testwrap_example import sample_text
3 dedented_text = textwrap.dedent(sample_text).strip()
4 for width in [45,70]:
5     print '%d  Columns:
' % width
6     print textwrap.fill(dedented_text, width=width)
7     print 

运行结果:

5、悬挂缩进

不仅输出的宽度可以设置,还可以单独控制第一行的缩进,以区分后面行

1 import textwrap
2 from testwrap_example import sample_text
3 dedented_text = textwrap.dedent(sample_text).strip()
4 print textwrap.fill(dedented_text, 
5                     initial_indent = '',
6                     subsequent_indent = '*'*4,
7                     width =75 )

运行结果:

这样一来会生成已走过悬挂缩进,即第一行与其他行不同;缩进可以包含空格和其他非空白字符

原文地址:https://www.cnblogs.com/victroy/p/4014803.html