问题描述
所以我只是重新格式化了一堆代码以合并textwrap.wrap,却发现我所有的\ n都消失了.这是一个例子.
So I just reformatted a bunch of code to incorporate textwrap.wrap, only to discover all of my \n are gone. Here's an example.
from textwrap import wrap
def wrapAndPrint (msg, width=25):
""" wrap msg to width, then print """
message = wrap(msg, width)
for line in message:
print line
msg = ("Ok, this is a test. Let's write to a \nnewline\nand then "
"continue on with this message")
如果我打印味精,我得到以下信息
If I print msg, I get the following
>>> print msg
Ok, this is a test. Let's write to a
newline
and then continue on with this message
>>>
但是,如果我将其包装,它看起来像这样:
However, if i send it to be wrapped it looks like this:
>>> wrapAndPrint(msg)
Ok, this is a test. Let's
write to a newline and
then continue on with
this message
>>>
我认为这可能与从列表中打印字符串有关,所以我尝试调用特定的索引,因此我尝试使for循环看起来更像这样:
I thought it might have something to do with printing strings from a list, so I tried calling specific indices, so I tried making my for loop look more like this:
x = 0
for line in message:
print line[x]
x += 1
但这并没有什么区别.那么,我在这里想念的还是做错了什么?我确实需要换行符,也确实需要包装文本.
But that didn't make any bit of difference. So, what am I missing here, or doing wrong? I really need my newlines, and I also really need my text to be wrapped.
推荐答案
默认情况下,wrap()
函数用单个空格替换空格字符(包括换行符).您可以通过传递关键字参数replace_whitespace=False
来关闭此功能.
By default, the wrap()
function replaces whitespace characters (including newline) with a single space. You can turn this off by passing the keyword argument replace_whitespace=False
.
http://docs.python.org/library/textwrap. html#textwrap.TextWrapper.replace_whitespace
这篇关于Python textwrap.wrap导致\ n出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!