Python String Literals: Quotes and Escapes
Core idea
A string (str) is text represented as a sequence of Unicode code points. A literal is the source-code notation for a value. Surround ordinary text with matching single or double quotes; the delimiters are not part of the stored text. Choose the delimiter that makes an embedded quote easy to read.
label = "Mina's bag"quote = 'She said "yes".'print(label)print(quote)Double quotes allow the apostrophe in the first string; single quotes allow the double quotes in the second. Both results are strings.
Escape a quote and insert a newline
A backslash before the matching quote keeps it inside the text. The escape \n represents a newline, not two printed characters. Triple-quoted strings can also contain actual line breaks.
Preserve backslashes
The raw prefix r preserves backslashes in this example. In the ordinary string, \\ represents one backslash. Neither expression opens a file.
Common mistake
Raw strings are not a way to ignore all syntax rules. For example, a raw literal cannot end with an odd number of backslashes before its closing delimiter. Empty text is written as ""; it is not the same as a space.
Practice
Write the text Sara said "hello". using single quotes, then write it using double quotes and escapes. Print both versions and compare the visible text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
String literals and escapes
Check your understanding of string literals.
Which literal contains the text Mina's bag?
What is printed?
print("red\nblue")What is printed?
print(r"a\b")Which source notation represents empty text?