在Python 2.7中将长行文本分成固定宽度的行

时间:2013-05-01 14:20:30

标签: python string text python-2.7 format

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

所以,对于一个工作函数,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!

1 个答案:

答案 0 :(得分:5)

有一个标准的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!
>>>