Escape characters

Let’s say that we want to print the path to the directory C:\nature. Consider what happens when we try to print the path:

>>> print("C:\nature")
C:
ature

In the example above, Python interpreted the \n characters as special characters. These characters are not meant to be displayed on the screen; they are used to control the display. In our case, the \n characters were interpreted as a new line.

The backslash (\) character is used in Python to escape special characters. So in our example, we would use the following code to print the path:

>>> print("C:\\nature")
C:\nature

Here is another example. What if we have a string that uses double-quotes and you want to put a double-quote inside the string:

>>> print("She said: "I love you very much."")
 
SyntaxError: invalid syntax

In the example above, Python thinks that the second double quote ends the string. To rectify this, we need to escape the double quotes inside the string with backslash:

>>> print("She said: \"I love you very much.\"")
She said: "I love you very much."
Geek University 2022