python - 在 Python 中包装多行字符串(保留现有的换行符)?

标签 python string word-wrap

考虑这个例子:

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 ??']

换行符似乎被保留,但作为“内联”字符;所以这里的第一个元素本身就是一个多行字符串——所以它不是我所要求的,每一行都是一个数组元素。

最佳答案

只需在拆分后添加换行符:

import textwrap
import pprint
import itertools

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 ??"""

wrapper = textwrap.TextWrapper(width = 80)
mylist = [wrapper.wrap(i) for i in mystr.split('\n') if i != '']
mylist = list(itertools.chain.from_iterable(mylist))

pprint.pprint(mylist)

输出:

['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 ??']

关于python - 在 Python 中包装多行字符串(保留现有的换行符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863889/

相关文章:

c++ - 如何为自定义字符串类型编写构造函数/赋值运算符重载?

wpf - 如何获取带有换行而不是截断文本的单元格的 WPF Datagrid?

html - 如何对齐两个 div(一个固定,另一个带有 break word 属性)?

css - 容器 DIV 未垂直环绕

python - 如何确定 struct.unpack 的格式(因为我没有用 Python 打包)?

python - 创建一个 Excel 在打开时不会改变数据的 csv 文件

mysql搜索字符串类似于php中的in_array

c# - 如何在 UTF-8 字节数组中找到字符串的起始索引? (C#)

python - 如何禁止在 Python/Tk 程序中选择文本?

python - leetcode : add-two-numbers using linked list