如何在可能的空格处拆分一个长字符串,如果没有,则插入连字符,并对除第一行之外的所有行进行缩进?
所以,对于一个工作函数,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/