6

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

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

1 回答 1

12

有一个标准的 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!
>>>
于 2013-05-01T15:06:12.860 回答