textwrap函数

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

 

纯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.

 

转载于:https://my.oschina.net/zhengtong0898/blog/513496

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值