Academic Resource Center

Escape Sequences in Python

Updated on

In Python a string is written in quotes. Sometimes we may want to include an apostrophe, quote, a tab or a new line.

Example code:

Escape Sequences in Python.pdf - Google Drive - Google Chrome

One way of fixing this is to use a different set of quotation marks.

Example code:

Escape Sequences in Python.pdf - Google Drive - Google Chrome

To include tabs, quotes, backslashes and new lines we would have to use some special character to let Python know we are inserting them. These special characters are called escape characters.

The escape character ‘\’ (backslash) is a special character that helps us include quotes. A backslash is added before the ‘ sign. (\’ or \”). Using it lets Python know that the following quotation mark ‘ or “ is not the end of the string. Escape characters will not be printed in the output.

Example code:

Escape Sequences in Python.pdf - Google Drive - Google Chrome

If we want to insert a new line in the string we would use \n.

Example code:

Escape Sequences in Python.pdf - Google Drive - Google Chrome

Escape characters at a glance:

Escape Sequence What does it do? Example code Output
\\ Prints backslash print('This is a backslash: \\') This is a backslash: \
\t Prints a tab print('This is a:\tTab') This is a    Tab
\’ Prints single quote print('A single quote: \'') A single quote: '
\” Prints double quotes print('A double quote: \"') A double quote: "
\n Inserts a new line print('First line\nSecond line') First line

Second line

Need More Help?

Click here to schedule a 1:1 with a tutor, coach, and or sign up for a workshop. *If this link does not bring you directly to our platform, please use our direct link to "Academic Support" from any Brightspace course at the top of the navigation bar.   

Previous Article Strings in Python
Next Article For Loops in Python
Have a suggestion or a request? Share it with us!