Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line break or "\n" is not working.

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)
like image 696
Mat Whiteside Avatar asked Jan 11 '14 20:01

Mat Whiteside


1 Answers

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)
like image 180
Siegfried Gevatter Avatar answered Sep 28 '22 05:09

Siegfried Gevatter