11. Escapes and quotes

Inside a string literal, a backslash \ starts an escape sequence: two characters that represent one special character. The backslash itself is not printed.

EscapeCharacter
\nnewline (moves to the next line)
\ttab
\\one literal backslash
\"a double quote inside a "..." string
\'a single quote inside a '...' string

Because a backslash is special, a Windows path must escape each one: "C:\\Users\\ada". To avoid escaping, prefix the string with r to make a raw string: r"C:\Users\ada". In a raw string every backslash is printed literally and escape sequences are not interpreted.

A quote only needs escaping when it is the same as the quote that opens the string. "She said \"hi\"" needs \", while 'She said "hi"' does not.

#01

Write a newline inside a string

\n is an escape sequence: it represents a newline inside a string, without ending the string.

Print "Line one" and "Line two" on two separate lines by putting \n between them in one string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Write a tab

\t is the escape sequence for a tab character. It moves the cursor to the next tab stop, so the two words are separated by a wide gap.

Print a string made of "Name", a tab and "Age".

The gap between the two words is one tab character, not a run of spaces.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Write a literal backslash

A backslash starts an escape sequence, so to print one backslash you write it twice: \\.

Print the path C:\Users\ada by escaping each backslash in the string.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Escape an apostrophe

When a string is written with single quotes, an apostrophe inside it must be escaped as \'.

Print It's "Python" using single quotes around the string and escaping the apostrophe.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Use a raw string

A raw string starts with r before the quotes. Escape sequences are not interpreted, so every backslash is printed exactly as written.

Print C:\new\table using a raw string, so \n and \t stay as backslashes instead of becoming a newline and a tab.

Print exactly:

Create a free account to save your progress and unlock chapter 2.