Line break or “\n” is not working.

◇◆丶佛笑我妖孽 提交于 2019-12-01 20:14:32

问题


Could you tell me why the line break \n isn't working?

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)

回答1:


The str() transformation is converting the "\n" into "\\n".

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

What's going on there? When you call str() on a list (same for tuple), that will call the __str__() method of the list, which in turn calls __repr__() on each of its elements. Let's check what its behaviour is:

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

So there you have the cause.

As for how to fix it, like Blender proposed, the best option would be to not use str() on the list:

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



回答2:


All the other answers are fixing a problem that shouldn't even exist. Translate your tuple of strings and ints into just a list of strings. Then, use str.join() to join them together into one big string:

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

print(''.join(bar))



回答3:


use this

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



回答4:


Use itemsToWriteToFile.replace('\\n', "") instead of itemsToWriteToFile.replace('\n', "")

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

Final Output:-

>>> print(itemsToWriteToFile)
'Number 1:' 12 'Number 2: ' 13 'Number 3: ' 13 'Number 4: ' 14



回答5:


I had this problem too and I solved it by making the following changes:

  1. Changing my Charfield to a TextField in my model
  2. Adding the model to my admin panel so that when editting the field I could press [Enter] manually in the value instead of using '\n'

Then using {{value|linebreaks}} finally worked. Guess \n in the string didnt work because of Sigfried's answer above.



来源:https://stackoverflow.com/questions/21067781/line-break-or-n-is-not-working

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