Escape Sequences
Escape sequences are two-character combinations (backslash plus another character) that tell Python to interpret the second character specially rather than literally.
Try it: Escape Sequences in String Literals
How Python turns the text of a string literal into characters: the tokenizer first finds where the literal ends (a backslash protects the next character; an unescaped inner quote or a line break in '…' ends it or breaks it), then each escape — \n, \t, \\, \', \", \xhh, \uXXXX, \N{name}, octal — becomes ONE character, a backslash at the end of a line joins lines, unknown escapes keep their backslash, and a raw string keeps everything as typed; len(), repr() and print() then show the result.
How it works
- The tokenizer scans for the closing quote: a backslash always skips the next character, so \' does not end a '…' string; an unescaped copy of the opening quote ends it (anything after is read as code), and a real line break inside '…' or "…" is 'unterminated string literal'. Triple quotes may span lines.
- The body is then decoded left to right: \n newline, \t tab, \\ one backslash, \' and \" quotes, \r, \a, \b, \f, \v, \ooo octal, \xhh (exactly 2 hex digits), \uXXXX, \UXXXXXXXX and \N{name} — each is ONE character.
- A backslash followed by a line break disappears (the source lines are joined); a backslash before a character that is not an escape is kept, with a SyntaxWarning; a truncated \x, \u or \U escape is a SyntaxError that names its positions.
- An r prefix makes a raw string: backslashes are kept as typed (but a raw string still cannot end in an odd backslash).
- len(s) counts the stored characters; repr(s) — what the interpreter echoes — writes invisible characters back as escapes; print(s) shows the characters themselves (line breaks, tab stops).
Default run (16 steps): Python reads a string literal opened by a single quote ('). First the tokenizer looks for where it ends; then the characters between the quotes are decoded. … print(s) shows the characters themselves: each newline starts a new line.
Simplified: One assignment s = <literal> of up to 80 characters and 4 lines, typed from printable ASCII plus a few accented letters and symbols; no f-strings or bytes. The lab's own tokenizer and decoder read the text — nothing is executed. Its value, len, repr, warnings and SyntaxError messages match CPython 3.12 on 2,500+ literals; \N{...} knows only 13 character names, and when the text after an early closing quote is an operator, keyword, f-string or new line the lab stops without saying what Python does next. print() output of invisible characters is shown as [\x..].
Loading the simulation…
When Strings Need Help
A string is written between quote characters, but sometimes the text you want to store also contains a quote, a new line, a tab, or a backslash. Python needs a way to distinguish the characters that control the string from the characters that belong inside it. Escape sequences provide that signal.
What do you think happens?
What do you think happens when Python reads the backslash in the sequence \" inside a double-quoted string?
Reveal answer
The quote is interpreted specially so it can be part of the string
An escape sequence combines a backslash with the following character. The pair tells Python to interpret the second character specially rather than literally.
Reading Escape Pairs
An escape sequence is a two-character combination: a backslash followed by another character. Python uses the pair to give the second character a special meaning instead of treating it literally. The most common pairs in this topic are \' for a single quote, \" for a double quote, \\ for a backslash, \n for a newline, and \t for a tab.
| Escape sequence | Meaning |
|---|---|
| \' | Single quote |
| \" | Double quote |
| \\ | Backslash |
| \n | Newline |
| \t | Tab |
Common escape sequences
Quotes Inside Quotes
The most common reason to use an escape sequence is to place a quote inside a string delimited by the same kind of quote. If a string starts with a single quote, an unescaped single quote later in the text can be read as the closing delimiter. Escaping that inner quote tells Python that it belongs to the string content instead.
Writing an Apostrophe
Create a string containing the text What's your name? using single quotes as the delimiters.
- 1Start the string
Use a single quote to begin the string.
- 2Protect the apostrophe
Write \' for the apostrophe in What's. The backslash prevents that apostrophe from being treated as the end of the string.
- 3Finish the string
Use the final single quote after the question mark as the closing delimiter.
The string can be written as 'What\'s your name?'.
| Approach | Code | When it works |
|---|---|---|
| Change the delimiter | "What's your name?" | The text contains a single quote, and the string is delimited by double quotes |
| Escape the inner quote | 'What\'s your name?' | The string is delimited by single quotes, so the inner single quote must be escaped |
| Escape double quotes | "She said, \"Hello!\"" | The text contains double quotes inside a double-quoted string |
Choosing a delimiter or escaping an inner quote
Position Changes in Text
Some escape sequences change where later characters appear when the string is displayed. The sequence \n represents a newline, so following text appears on a new line. The sequence \t represents a tab, so following text is separated by a tab position. These sequences affect the string's displayed layout rather than adding the two visible characters backslash and letter as ordinary text.
message = "Name:\tAda\nRole:\tStudent"
print(message)- 1Python reads the string from left to right.
- 2It interprets each \t as a tab and the \n as a newline.
- 3print displays the resulting text with the changed positions.
- The first \t creates a tab separation after Name:.
- The \n moves the following text to a new line.
- The second \t creates a tab separation after Role:.
Name: Ada
Role: StudentA backslash can also represent a literal backslash when it is paired with another backslash. For example, writing \\ in the source represents one backslash in the resulting string. This is useful when the text itself needs to contain backslashes.
Joining Source Lines
A single backslash at the end of a source-code line, with no trailing characters after it, continues the string onto the next source-code line. The line break in the source code does not add a newline character to the string value. This is different from writing \n inside the string: \n deliberately represents a newline in the resulting text.
This text continues onto the next source line.Missing and Misused Escapes
Common mistake Putting an unescaped apostrophe inside a single-quoted string
What it looks like'What's your name?'Why it failsPython sees the apostrophe after What as the end of the string. The remaining text is then not parseable as part of that string.
Do this insteadUse 'What\'s your name?' or use double quotes: "What's your name?".
Common mistake Putting unescaped double quotes inside a double-quoted string
What it looks like"She said, "Hello!""Why it failsThe inner double quote can be interpreted as the closing delimiter rather than as string content.
Do this insteadEscape the inner quotes: "She said, \"Hello!\"".
Common mistake Writing one backslash when the string must contain a literal backslash
What it looks like"C:\Users\Student"Why it failsA backslash begins an escape sequence, so it is not automatically treated as an ordinary backslash character.
Do this insteadUse two backslashes for one literal backslash: "C:\\Users\\Student".
Common mistake Expecting a source-line continuation to display a newline
What it looks like"first line \ second line"
Why it failsA backslash at the end of the source line continues the string without adding a newline character.
Do this insteadUse \n when the resulting string should contain a newline.
If a string containing an apostrophe raises a syntax error, first inspect which quote character opened the string. Then check whether the same quote appears inside the text. Either escape the inner quote or choose the other quote type as the delimiter. The key debugging question is: which quote does Python think ends the string?
Escape Sequence Practice
Write Python string literals for each requested result: a string containing an apostrophe in What's next?, a string containing the quotation Hello!, a string containing one literal backslash, and a string with two displayed lines.
Hints
- Match the quote delimiter to the quote character inside the text, or escape the inner quote.
- Use two backslashes in the source when the resulting value needs one backslash.
- Use \n when the resulting text should contain a newline.
When checking your answer, read each string from left to right. Identify the opening delimiter, identify every backslash pair, and then identify the closing delimiter. This process helps you predict whether a quote belongs to the string, whether a backslash becomes literal text, and whether the displayed result contains a new line or tab.
Working Rules
- 1An escape sequence is a backslash followed by another character, and Python interprets the pair specially.
- 2Use escaped quotes when the text contains the same quote character used as the string delimiter.
- 3Use \\ for one literal backslash, \n for a newline, and \t for a tab.
- 4A backslash at the end of a source line continues the string without adding a newline to its value.
- 5When debugging, check which quote Python sees as the string's closing delimiter.
Key Takeaways
- Escape sequences use a backslash and a following character to give that character a special interpretation.
- Escaped quotes allow quote characters to appear inside strings without ending them.
- The sequences \\, \n, and \t represent a literal backslash, a newline, and a tab.
- A backslash at the end of a source line joins the next line without placing a newline in the string value.
- Most quote-related syntax errors happen because Python interprets an unescaped inner quote as the end of the string.