Escape Characters

 

Sometimes we may need to print some special “unprintable” characters such as a tab or a newline. In this case, you need to use the \ (backslash) character to escape characters that otherwise have a different meaning.

 

For instance to print a tab, we type the backslash character before the letter t, like this: \t. Without the \ character, the letter t will be printed. With it, a tab is printed. Hence, if you type print (‘Hello\tWorld’), you’ll get Hello      World

 

Other common uses of the backslash character are shown below.

>>> shows the command and the following lines show the output.

 

\n (Prints a newline)

 

>>> print (‘Hello\nWorld’)

Hello

World

 

\\ (Prints the backslash character itself)

>>> print (‘\\’)

\

 

\” (Prints double quote, so that the double quote does not signal the end of the string)

 

>>> print (“I am 5'9\" tall”)

I am 5’9” tall

 

\’ (Print single quote, so that the single quote does not signal the end of the string)

 

>>> print (‘I am 5\’9” tall’)

I am 5’9” tall

 

If you do not want characters preceded by the \ character to be interpreted as special characters, you can use raw strings by adding an r before the first quote. For instance, if you do not want \t to be interpreted as a tab, you should type print (r‘Hello\tWorld’). You will get Hello\tWorld as the output.