Search code examples
pythonline-breaks

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)

Solution

  • 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)