Hol*_*rel 2 python string format text python-2.7
我如何在可能的空间分解长字符串,如果没有,插入连字符,除了第一行以外的所有行都有缩进?
所以,对于一个工作函数,breakup():
splitme = "Hello this is a long string and it may contain an extremelylongwordlikethis bye!"
breakup(bigline=splitme, width=20, indent=4)
Run Code Online (Sandbox Code Playgroud)
输出:
Hello this is a long
string and it
may contain an
extremelylongwo-
rdlikethis bye!
Run Code Online (Sandbox Code Playgroud)
有一个标准的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!']
>>>
Run Code Online (Sandbox Code Playgroud)
但是,在破坏单词时不会插入连字符.该模块有一个快捷功能fill,它连接生成的列表,wrap所以它只是一个字符串.
>>> print textwrap.fill(splitme, width=10)
Hello this
is a long
string and
it may
contain an
extremelyl
ongwordlik
ethis bye!
Run Code Online (Sandbox Code Playgroud)
要控制缩进,请使用关键字参数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!
>>>
Run Code Online (Sandbox Code Playgroud)