Search code examples
pythonnewlineword-wrap

Python textwrap.wrap causing issue with \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
>>>

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.


Solution

  • 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