Representing Special Characters in Strings
An escape sequence starts with a backslash (\) followed by one or more characters that Python interprets specially. It lets a string literal represent characters such as a line break or a quote that would otherwise end the literal.
The backslash changes how Python parses the following characters. It is part of the source notation, while the resulting string contains the character represented by that notation.
Problems in String Writing
Quotes and backslashes need care inside a string, because Python reads them before the string exists. An inner quote that matches the delimiter closes the literal too early, and a backslash in an ordinary string starts escape notation. Escaping the character keeps it in the text, and writing two backslashes keeps one backslash in the value.
Quote Conflicts
When the same quote character both delimits a string and appears inside it, an unescaped inner quote closes the literal too early. The remaining characters are then parsed as invalid Python code.
# Problem: single quote inside string
>>> 'I'm Bob.'
SyntaxError: invalid syntax
# Solution: use double quotes for string
>>> "I'm Bob."
"I'm Bob."
# Problem: both types of quotes in string
>>> 'He said: "I'm Bob."'
SyntaxError: invalid syntaxWhen you use single quotes to create a string, but there's also a single quote inside that string, Python will consider the second quote as the string closer. As a result, the part after it is considered invalid code.
Solution with Backslash
Place a backslash (\) before an inner quotation mark. Python reads the escaped quote as part of the string instead of its closing delimiter.
# Using escape sequence for single quote
>>> 'He said: "I\'m Bob."'
'He said: "I\'m Bob."'
# print displays the string value after escape processing
>>> print('He said: "I\'m Bob."')
He said: "I'm Bob."In this example, \' tells Python to keep the single quote inside the text. The string continues after that quote.
Displaying Backslash Characters
Since backslash has a special meaning in escape sequences, how do you display the backslash itself? You need to use two backslashes consecutively.
# Displaying backslash in string
>>> print('The escape sequence for a new line is \\n.')
The escape sequence for a new line is \n.
# Using raw string (prefix r)
>>> text = r'The escape sequence for a new line is \n.'
>>> text
'The escape sequence for a new line is \\n.'
>>> print(text)
The escape sequence for a new line is \n.A raw string prefix such as r keeps most backslashes as written. Quotes still have to fit the literal's delimiter rules, and a raw string cannot end with an odd number of backslashes.
Escape Sequence Reference
These escape sequences represent characters in Python string literals:
| Escape Sequence | Meaning |
|---|---|
\' | Single quote (') |
\" | Double quote (") |
\n | New line (newline) |
\r | Carriage return |
\t | Horizontal tab |
\b | Backspace |
\\ | Backslash character () |
\uxxxx | Unicode character with a four-digit hexadecimal code point |
\Uxxxxxxxx | Unicode character with an eight-digit hexadecimal code point |
\N{name} | Unicode character by its registered name |
\xhh | Character with a two-digit hexadecimal value |
Each escape sequence has a specific function to control the display or format of text in programs.
Escaping Curly Braces in Format Strings
In str.format() and f-strings, curly braces delimit replacement fields. Doubling a brace escapes it for the formatting syntax. This is separate from backslash escape sequences in string literals.
# Escaped curly braces in a format string: {{ }}
>>> '{{}}'.format('text')
'{}'
# Displaying text with curly braces
>>> '{{{}}}'.format('text')
'{text}'Write {{ to produce { and }} to produce }. In '{{{}}}', the outer doubled braces become literal braces while the middle {} remains a replacement field.
Combining Escape Sequences
The example below uses escape sequences to control tabs and line breaks alongside quotation marks and literal backslashes in one output.
# Creating formatted output with tab and newline
print("Name\t: John Doe")
print("Age\t: 25 years")
print("Address\t: Jakarta\n")
# Displaying dialog with quotation marks
print('He said: "Today the weather is very bright!"')
# Displaying file path with backslash
print("File saved at: C:\\Users\\Documents\\data.txt")
# Combination of various escape sequences
print("First line\nSecond line\t(with tab)\nThird line")In this example, \t creates neat columns, \n separates lines, and \\ displays Windows file paths correctly.
The key distinction is between source notation and the resulting string. \n, for example, occupies two characters in the source but represents one newline character in the string.