每日一“酷”之textwrap

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

1 创建实例数据

1sample_text ='''2I’m very happy and I like to make friends with others.3I 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.4What a pity!At school, I study Chinese,math, English, history, politics and so on. I like all of them.5I often help my teacher take care of my class and I think I am a good helper.6I live with my parents and we go home on time every day.7'''

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

2 填充段落

1importtextwrap2fromtestwrap_exampleimportsample_text3PRint'No dedent: \n'4printtextwrap.fill(sample_text, width=50)

运行结果:

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

3、去除现有缩进

1importtextwrap2fromtestwrap_exampleimportsample_text3dedented_text =textwrap.dedent(sample_text)4print'Dedented: \n'5printdedented_text

运行结果:

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

执行前(!代表空格):

!aaa

!!!aaa

!bbb

执行后:

aaa

!!aaa

bbb

4、结合dedent 和 fill

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

1importtextwrap2fromtestwrap_exampleimportsample_text3dedented_text =textwrap.dedent(sample_text).strip()4forwidthin[45,70]:5print'%d Columns:\n'%width6printtextwrap.fill(dedented_text, width=width)7print

运行结果:

5、悬挂缩进

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

1importtextwrap2fromtestwrap_exampleimportsample_text3dedented_text =textwrap.dedent(sample_text).strip()4printtextwrap.fill(dedented_text,5initial_indent ='',6subsequent_indent ='*'*4,7width =75 )

运行结果:

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航