Escape SequencesΒΆ

An escape sequence is a sequence of characters that Python applies special meaning to when they are encountered in a string. Several common escape sequences are listed below.

Escape Sequence

Result

\'

Prints a single quote.

\"

Prints a double quote.

\n

Inserts a newline.

\t

Inserts a tab.

\\

Inserts a backslash.

For an example use case for escape sequences, assume that we want to define a variable containing the following string of characters:

He yelled, "I've had enough!" before storming out of the room.

As before, the presence of double quotes within the string prohibit us from being able to use double quotes to define the string. Furthermore, since the character for the apostrophe is the same as the character for a single quote, we are now no longer able to use single quotes to define our string. One solution is to use an escape sequence for the apostrophe so that Python knows to interpret it as text.

sentence = 'He yelled, "I\'ve had enough!" before storming out of the room.'
print(sentence)
He yelled, "I've had enough!" before storming out of the room.

Had we wished, we could have escaped the double quotes within the string as well as the apostrophe. In this case, we could have used either single or double quotes to define our string.

We can use the \n escape sequence to insert a newline inside of a string.

tale2cities = "It was the best of times.\nIt was the worst of times."
print(tale2cities)
It was the best of times.
It was the worst of times.

We can use \t to insert tabs in our string. This can be used for indenting lines, or for aligning output.

print("Regular.")
print("\tIndented.")
print("\t\tDouble indented.")
Regular.
	Indented.
		Double indented.

The tab escape sequence can be used to align portions of multi-line output. The following example shows how we might use tabs to align columns in the printout of an employee database.

print('ID\tEmployee Name\tSalary')
print('-------------------------------')
print('107\tJane Doe\t$54,000')
print('139\tJohn Smith\t$48,300')
print('162\tPat Jones\t$52,500')
ID	Employee Name	Salary
-------------------------------
107	Jane Doe	$54,000
139	John Smith	$48,300
162	Pat Jones	$52,500