我有一个很长的字符串:
S='Hello\n i have a very very very very..... very very very very.... long Text!'
打印此文本会创建一个长行,我想将该行分成最多10或20个字符的片段。我想用\n
打破这一行,并在新字符串中包含\n
。
我希望:
Hello
i have a very
very very very
..... very very
very very....
long Text!
答案 0 :(得分:0)
textwrap.wrap
允许您将字符串换行到某个width
。
默认情况下,它会在换行前用空格替换空格,包括换行符。
如果您想保留换行符等,请设置replace_whitespace=False
>>> import textwrap
>>> s = 'Hello\n i have a very very very very..... very very very very.... long Text!'
>>> print('\n'.join(textwrap.wrap(s, width=20, replace_whitespace=False)))
Hello
i have a very
very very very.....
very very very
very.... long Text!
(默认值:
True
)如果为true,则在制表符扩展之后但在换行之前,wrap()方法将用单个空格替换每个空格字符。替换的空白字符如下所示:制表符,换行符,垂直制表符,换页符和回车符('\t\n\v\f\r')
。注意如果
expand_tabs
为false且replace_whitespace为true,则每个制表符将替换为单个空格,这与制表符扩展不同。注意如果
replace_whitespace
为false,则换行符可能出现在行的中间并导致奇怪的输出。出于这个原因,文本应该分成段落(使用str.splitlines()或类似的),它们是分开包装的。
答案 1 :(得分:-2)
您可以使用'''YOUR BIG STRING IN PARAGRAPH WHAT YOU WANT'''
答案 2 :(得分:-3)
如果你想要的话,你也可以使用双引号而不是单引号。
s = """ this is a very
long string if I had the
energy to type more and more ..."""