1.1.4 - Escape Codes

If quotes are used to tell the computer the start and end of the string of text you wish to print, how does a program print out a set of double quotes? For example:

>>> print("I want to print a double quote " for some reason.")

This code doesn't work. The computer looks at the quote in the middle of the string and thinks that is the end of the text. Then it has no idea what to do with the commands for some reason and the quote and the end of the string confuses the computer even further.

It is necessary to tell the computer that we want to treat that middle double quote as text, not as a quote ending the string. This is easy, just prepend a backslash in front of quotes to tell the computer it is part of a string, not a character that terminates a string. For example:

>>> print("I want to print a double quote \" for some reason.")

This combination of the two characters \" is called an escape code. Almost every language has them. Because the backslash is used as part of an escape code, the backslash itself must be escaped. For example, this code does not work correctly:

>>> print("The file is stored in C:\new folder")

Why? Because \n is an escape code. To print the backslash it is necessary to escape it like so:

>>> print("The file is stored in C:\\new folder")


What is a “Linefeed”? Try this example:

>>> print("This\nis\nmy\nsample.")

The output from this command is:

This
is
my
sample.

The \n is a linefeed. It moves “cursor” where the computer will print text down one line. The computer stores all text in one big long line. It knows to display the text on different lines because of the placement of \n characters.