【问题标题】:Python textwrap.wrap causing issue with \nPython textwrap.wrap 导致 \n 出现问题
【发布时间】:2012-10-15 19:19:47
【问题描述】:

所以我只是重新格式化了一堆代码以合并 textwrap.wrap,却发现我所有的 \n 都不见了。这是一个例子。

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

如果我打印 msg,我会得到以下信息

>>> print msg
Ok, this is a test. Let's write to a 
newline
and then continue on with this message
>>> 

但是,如果我把它送去包装,它看起来像这样:

>>> wrapAndPrint(msg)
Ok, this is a test. Let's
write to a  newline and
then continue on with
this message
>>>

我认为这可能与打印列表中的字符串有关,所以我尝试调用特定的索引,因此我尝试让我的 for 循环看起来更像这样:

x = 0
for line in message:
  print line[x]
  x += 1

但这并没有什么不同。那么,我在这里错过了什么,或者做错了什么?我真的需要我的换行符,我也真的需要我的文字被换行。

【问题讨论】:

    标签: python newline word-wrap


    【解决方案1】:

    默认情况下,wrap() 函数将空白字符(包括换行符)替换为单个空格。您可以通过传递关键字参数 replace_whitespace=False 来关闭它。

    http://docs.python.org/library/textwrap.html#textwrap.TextWrapper.replace_whitespace

    【讨论】:

    • 该死,我怎么错过了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 2015-09-07
    • 2012-11-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多