Python textwrap.wrap causing issue with \n

谁说我不能喝 提交于 2019-12-13 15:19:15

问题


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

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.


回答1:


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



来源:https://stackoverflow.com/questions/12902521/python-textwrap-wrap-causing-issue-with-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!