【问题标题】:Line break or "\n" is not working.换行符或“\n”不起作用。
【发布时间】:2014-01-11 20:57:05
【问题描述】:

你能告诉我为什么换行符 \n 不起作用吗?

itemsToWriteToFile = "Number 1:", 12, "\nNumber 2: ", 13, "\nNumber 3: ", 13, "\nNumber 4: ", 14
itemsToWriteToFile = str(itemsToWriteToFile)

itemsToWriteToFile = itemsToWriteToFile.replace('(', "")
itemsToWriteToFile = itemsToWriteToFile.replace(')', "")
itemsToWriteToFile = itemsToWriteToFile.replace('"', "")
itemsToWriteToFile = itemsToWriteToFile.replace(',', "")
itemsToWriteToFile = itemsToWriteToFile.replace('\n', "")

print(itemsToWriteToFile)

【问题讨论】:

  • 你为什么首先将字符串和整数的元组转换为字符串?你的目标是什么?
  • 哦,对不起......完全看到这个出现在 JS 标签中。 (删除原始评论)。
  • DSM,代码是从我的原始程序稍微编辑的,所以更有意义。

标签: python line-breaks


【解决方案1】:

str() 转换正在将“\n”转换为“\\n”。

>>> str('\n')
'\n'
>>> str(['\n'])
"['\\n']"

那里发生了什么?当您在列表上调用 str() 时(对于元组也是如此),这将调用列表的 __str__() 方法,该方法又在其每个元素上调用 __repr__()。让我们检查一下它的行为:

>>> "\n".__str__()
'\n'
>>> "\n".__repr__()
"'\\n'"

所以你有原因。

至于如何修复它,就像 Blender 建议的那样,最好的选择是不在列表中使用str()

''.join(str(x) for x in itemsToWriteToFile)

【讨论】:

  • 为什么在使用str()的时候要加第二个“\”?
  • 我已经更新了我的答案。至于 str.__repr__ 的行为,我找不到任何解释它的参考资料,但它有点道理,因为您想要可视化字符串的内容,而不是实际的字符串。
  • 这是不正确的。你不应该一开始就更换这些。
  • 问题问为什么 OP 的代码不起作用,这就是我的回答。
  • 这个答案就是我要找的;其他都是有用的提示。
【解决方案2】:

所有其他答案都在解决一个甚至不应该存在的问题。将您的字符串和整数元组转换为字符串列表。然后,使用str.join() 将它们连接成一个大字符串:

foo = "Number 1:", 12, "\nNumber 2: ", 13, "\nNumber 3: ", 13, "\nNumber 4: ", 14
bar = map(str, foo)

print(''.join(bar))

【讨论】:

  • 我知道你在那里做了什么。感谢您的建议。
  • 这个答案很好,但我不会说它比齐格弗里德的好。我用谷歌搜索“python换行不起作用”并得到了这个问题。对 OP 代码的优化对我来说毫无意义,而且我怀疑大多数人。知道str('\n') 返回'\n' 会更有用。
  • @gwg:这不是优化。如果您想将事物连接在一起,请使用str.join()。 (Ab) 使用 str(itemsToWriteToFile) 然后删除括号、逗号和引号是错误的做法。这就像使用eval(str(a) + ' * ' + str(b)) 将两个数字相乘。
【解决方案3】:

使用这个

itemsToWriteToFile = itemsToWriteToFile.translate(None, "(),\"\\n")

【讨论】:

    【解决方案4】:

    使用itemsToWriteToFile.replace('\\n', "") 代替itemsToWriteToFile.replace('\n', "")

    >>itemsToWriteToFile = itemsToWriteToFile.replace('\\n', "")
    
    Final Output:-
    
    >>> print(itemsToWriteToFile)
    'Number 1:' 12 'Number 2: ' 13 'Number 3: ' 13 'Number 4: ' 14
    

    【讨论】:

      【解决方案5】:

      我也遇到了这个问题,我通过以下更改解决了这个问题:

      1. 在我的模型中将 Charfield 更改为 TextField
      2. 将模型添加到我的管理面板,以便在编辑字段时我可以在值中手动按 [Enter] 而不是使用“\n”

      然后使用 {{value|linebreaks}} 终于奏效了。由于上面 Sigfried 的回答,猜测字符串中的 \n 不起作用。

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 2018-03-09
        • 2020-06-27
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        相关资源
        最近更新 更多