在 Python 中包装多行字符串(保留现有的换行符)? [英] Wrap multiline string (preserving existing linebreaks) in Python?

查看:35
本文介绍了在 Python 中包装多行字符串(保留现有的换行符)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

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 已经是一个多行字符串,因为它包含换行符;但是,如果我运行这个脚本,我会得到输出:

The string mystr is already a multiline string, given that it contains linebreaks; however, if I run this script, I get as output:

[' 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 首先加入"多行字符串(即删除其中现有的换行符),然后才将其包裹(即在给定的位置拆分它)字符数).

... which means that textwrap.wrap first "joined" the multiline string (that is, removed the existing linebreaks in it), and only then wrapped it (i.e. split it at the given number of characters).

如何包装多行字符串以保留换行符?也就是说,在这种情况下,预期的输出是:

How can I wrap a multiline string, such that the line feeds are preserved? that is, in this case, the expected output would be:

['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 的评论,我试过了:


EDIT; thanks to comment by @u_mulder, I tried:

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

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

The line breaks seem to be preserved, but as "inline" characters; so here the first element is a multiline string in itself -- and so it is not as I require it, with every line as an array element.

推荐答案

拆分后只需添加换行符:

Just add the newlines back after splitting:

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 中包装多行字符串(保留现有的换行符)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆