我如何在可能的空格处打断一个长字符串,如果没有则插入连字符,并且除了第一行之外的所有行都缩进?
因此,对于工作函数,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 模块可以执行此操作: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_indent
和 subsequent_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!
>>>
关于python - 在 Python 2.7 中将长文本行分解为固定宽度的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319878/