考虑以下例子:
import textwrap
import pprint
mystr=r"""
First line.
Second line.
The third line is a very long line, which I would like to somehow wrap; wrap at 80 characters - or less, or more! ... can it really be done ??"""
pprint.pprint(textwrap.wrap(mystr,80))
字符串mystr
已经是一个多行字符串,因为它包含换行符;但是,如果我运行这个脚本,我会得到以下输出:
[' First line. Second line. The third line is a very long line, which I would like',
'to somehow wrap; wrap at 80 characters - or less, or more! ... can it really be',
'done ??']
这意味着textwrap.wrap
首先“连接”多行字符串(即删除其中的现有换行符),然后才将其包装(即在给定的字符数处分割它)。
我如何包装一个多行字符串,以保留换行符?也就是说,在此情况下,预期输出应该是:
['First line.',
'Second line.',
'The third line is a very long line, which I would like to somehow wrap; wrap at',
'80 characters - or less, or more! ... can it really be done ??']
编辑:感谢 @u_mulder 的评论,我尝试了以下方法:
textwrap.wrap(mystr,80,replace_whitespace=False)
并且我获得了:
['\nFirst line.\nSecond line.\nThe third line is a very long line, which I would like',
'to somehow wrap; wrap at 80 characters - or less, or more! ... can it really be',
'done ??']
换行符似乎被保留了,但作为“内联”字符;因此,这里的第一个元素本身是多行字符串——所以它不像我需要的那样,每一行都作为一个数组元素。
pprint - 支持递归地漂亮打印列表、元组和字典
(而不是字符串)。并且help(textwrap.wrap)
给出了将单个段落文本包装起来,返回一个包含已包装行的列表。
因此我们可以看到它期望输入字符串中只有一个段落,而不是多个段落。 - mtrw