博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
每日一“酷”之textwrap
阅读量:6919 次
发布时间:2019-06-27

本文共 1831 字,大约阅读时间需要 6 分钟。

介绍:需要美观打印时,可以使用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 textwrap2 from testwrap_example import sample_text3 print 'No dedent: \n'4 print textwrap.fill(sample_text, width=50)

运行结果:

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

3、去除现有缩进

1 import textwrap2 from testwrap_example import sample_text3 dedented_text = textwrap.dedent(sample_text)4 print 'Dedented: \n'5 print dedented_text

运行结果:

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

执行前(!代表空格):

!aaa

!!!aaa

!bbb

执行后:

aaa

!!aaa

bbb

4、结合dedent 和 fill

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

1 import textwrap2 from testwrap_example import sample_text3 dedented_text = textwrap.dedent(sample_text).strip()4 for width in [45,70]:5     print '%d  Columns:\n' % width6     print textwrap.fill(dedented_text, width=width)7     print

运行结果:

5、悬挂缩进

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

1 import textwrap2 from testwrap_example import sample_text3 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

你可能感兴趣的文章
ELK(ElasticSearch+Logstash+Kibana)+redis日志收集分析系统
查看>>
nginx部署
查看>>
ClusterControl DB 集群测试
查看>>
dot 学习笔记二
查看>>
Qt学习之路(20): 事件接收与忽略
查看>>
懒人建站之电视直播插件
查看>>
Java迭代器
查看>>
IOS开发之UIImageView
查看>>
Redis的初步安装
查看>>
jQuery键盘控制方法,以及键值(keycode)对照表
查看>>
Android 踩坑记录
查看>>
mysql 大数据查询的解决方式
查看>>
web用户登录测试用例设计
查看>>
Windows 10下搭建Maven 私服仓库
查看>>
提交自己的pods到公共的cocoapods
查看>>
Nivo Slider 使用文档说明 jq简单幻灯片切换
查看>>
用phpMyadmin创建独立的数据库帐号
查看>>
web安全
查看>>
lucene自定义分词器
查看>>
Java集合框架学习总结
查看>>