The escape character starts a sequence. So when Python sees the \ it begins looking forwards to the next character to read together with the \ as a sequence. Anything you put after it will be interpreted as an escape sequence. You can try \a \r \q \b \. \! \? \~, all of these Python will read as an escape sequence, because the \ told Python to “start looking for an escape sequence”.
Not all of those are actually valid escape sequences, though. There doesn’t exist instructions for every conceivable escape sequence. When Python receives an invalid escape sequence, it leaves the backslash in. So in this instance:
print(“The escape character is \.”)
Python has read an escape sequence: \. (a backslash followed by a period), but Python doesn’t recognize this escape sequence, so it has been left in. Similarly:
print(“The escape character is \/”)
Python reads the escape sequence \/ (a backslash followed by a forward slash), which is once again an invalid escape sequence. Python leaves it in. Your following example:
print(“The escape character is \r”)
reads the escape sequence \r (a backslash followed by an r), which is a valid escape sequence. Python interprets this sequence to be a carriage return.
The way you characterized the escape sequence for the first two (as working) and the last one (as not working) is actually backwards. The first two are not working: they aren’t valid escape sequences. You’re telling Python to interpret escape sequences that have no instructions. The last one did work: Python read the escape sequence and provided a carriage return. Try this command:
print(“I like tacos.\nBut I also love burritos.”)
The backslash here starts an escape sequence: \n. This escape sequence returns a linefeed, effectively like pressing the enter or return key. But change it to:
print(“I like tacos.\zBut I also love burritos.”)
and it no longer works. You’ve given Python an invalid escape sequence. If you still see your escape sequence in the string, then Python didn’t do anything with it. This means you have a bug and should correct the escape sequence, or remove it.
By the way, by using the \ in your posts here, the forum backend is interpreting escape sequences. That’s why your \ keeps disappearing from your posts. Because, unlike Python, even invalid escape sequences are removed, which is typical behavior. These forums are providing a perfect sandbox for you to understand why you need to escape the escape character. Whenever you see \ in my post, I’m actually typing \\ in the editor.