【问题标题】:Break up long line of text into lines of fixed width in Python 2.7在 Python 2.7 中将长文本行拆分为固定宽度的行
【发布时间】:2025-12-07 03:00:02
【问题描述】:

我将如何在可能的空格处分解一个长字符串,如果没有,则插入连字符,除第一行之外的所有行都缩进?

所以,对于一个工作函数,breakup():

splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
breakup(bigline=splitme, width=20, indent=4)

会输出:

Hello this is a long
    string and it
    may contain an
    extremelylongwo-
    rdlikethis bye!

【问题讨论】:

    标签: python string text python-2.7 format


    【解决方案1】:

    有一个标准的 Python 模块可以做到这一点:textwrap:

    >>> import textwrap
    >>> splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
    >>> textwrap.wrap(splitme, width=10)
    ['Hello this', 'is a long', 'string and', 'it may', 'contain an', 'extremelyl', 'ongwordlik', 'ethis bye!']
    >>> 
    

    不过,它不会在分词时插入连字符。该模块有一个快捷函数fill,它将wrap生成的列表连接起来,所以它只是一个字符串。

    >>> print textwrap.fill(splitme, width=10)
    Hello this
    is a long
    string and
    it may
    contain an
    extremelyl
    ongwordlik
    ethis bye!
    

    要控制缩进,请使用关键字参数initial_indentsubsequent_indent

    >>> print textwrap.fill(splitme, width=10, subsequent_indent=' ' * 4)
    Hello this
        is a
        long
        string
        and it
        may co
        ntain
        an ext
        remely
        longwo
        rdlike
        this
        bye!
    >>>
    

    【讨论】:

    • 太好了,感谢您的解释和示例。我不知道 textwrap 模块。这几乎是我想要的,可惜它不支持长词的连字符。
    最近更新 更多