首页 > 其他 > 详细

textwrap函数

时间:2015-10-04 22:22:55      阅读:333      评论:0      收藏:0      [点我收藏+]

有时候需要对文本进行长度限制,避免每一行太长(影响阅读), 有什么好的方法吗?


纯Python的写法:

样例代码: 按指定宽度显示文本内容
# -.- coding:utf-8 -.-
__author__ = ‘zt‘
text = ‘Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.‘

width = 35
lines = len(text) // width
if len(text) % width:
    lines = (len(text) // width) + 1

for i in range(lines):
    print text[width * i:width * (i + 1)]

        
输出结果:
Use of this source code is governed
 by a BSD-style license that can be
 found in the LICENSE file.


函数式写法:

样例代码: 按指定宽度显示文本内容
# -.- coding:utf-8 -.-
__author__ = ‘zt‘


def wrap(text, width):
    # 初始化结果变量
    result = ‘‘
    
    # 计算应该迭代次数(即计算出需要输出几行)
    lines = len(text) // width

    # 求余, 如果余数大于0, 就在lines变量上+1
    if len(text) % width:
        lines = (len(text) // width) + 1

    # 按提供的width对原始文本进行切割.
    for i in range(lines):
        result += text[width * i:width * (i + 1)]+"\n"
    return result

if __name__ == ‘__main__‘:
    text = ‘Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.‘    
    print wrap(text, 50)
    
    
# 输出结果
Use of this source code is governed by a BSD-style
 license that can be found in the LICENSE file.



我不知道上述这两种写法是不是唯一的,但是我知道python函数库已经提供了textwrap函数,可以很简单的完成相同工作.

代码样例: 
# -.- coding:utf-8 -.-
__author__ = ‘zt‘
import textwrap

text = ‘Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.‘
print ‘\n‘.join(textwrap.wrap(text, width=50))

输出结果:
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.


textwrap函数

原文:http://my.oschina.net/u/2452965/blog/513496

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!