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)
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)
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))
use this
itemsToWriteToFile = itemsToWriteToFile.translate(None, "(),\"\\n")
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
I had this problem too and I solved it by making the following changes:
- Changing my Charfield to a TextField in my model
- 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.