Line break or “\\n” is not working.

2019-02-22 20:35发布

问题:

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.