Search code examples
pythonstringprintingescapingline-breaks

How to escape line break already present in a string?


I have a question, why does this:

testStr="\n"
testStr = "\\"+testStr
print testStr
>>> \

happen? Shouldn't it now print \n? I know about the repr() function, but I would rather solve this in another way It would be very kind if you could help me


Solution

  • After you type testStr = "\n" the special characters are already being interpreted. So in the next line you cannot change their interpretation as it already has happened. This is being done during lexical analysis stage, so even way before the code is actually executed. When the string is being assigned to your variable the two characters "\" and "n" are already gone - there is only one character - the new line character.