Python 标准库之 textwrap

textwrap 主要用于对文本进行自动换行、填充和缩进等操作。

wrap()

对 text (字符串) 中的单独段落自动换行以使每行长度最多为 width 个字符。 返回由输出行组成的列表,行尾不带换行符。简单理解就是对原 text 进行重新组织,每 width 个字符进行一次分割。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
    """

    print(textwrap.wrap(text, 3))  # ['   ', 'hel', 'lo', 'wor', 'ld!']

fill()

对 text 中的单独段落自动换行,并返回一个包含被自动换行段落的单独字符串。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
    """

    print(textwrap.fill(text, 3))
    #    
    # hel
    # lo
    # wor
    # ld!

shorten()

折叠并截短给定的 text 以符合给定的 width。将 text 缩短到指定的 width 长度内。如果缩短后的长度还是超过 width 的话,会用表示省略的占位符替换。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
    """

    print(textwrap.shorten(text, 11))  # hello [...]

dedent()

移除相同缩进。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
    """

    print(textwrap.dedent(text))
    # 
    # hello 
    #     world!

indent()

添加缩进。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
    """

    print(textwrap.indent(text, "+"))
    #
    # +        hello 
    # +            world!

对象重用

wrap()fill() 和 shorten() 的作用方式为创建一个新的 TextWrapper 实例并在其上调用单个方法。每个调用的对象不会重用,使用效率上不高。

import textwrap

if __name__ == '__main__':
    text = """
        hello 
            world!
            nice
            to 
            meet
            you
    """

    wrapper = textwrap.TextWrapper(initial_indent="* ", width=7, break_long_words=False, max_lines=3, subsequent_indent="--")
    print(wrapper.fill(text))
    # * hello
    # --world!
    # --[...]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值