Sub topic 10
Writing string literals
A string literal is text written directly in source code. This chapter covers the ways to write one: quote styles, escape sequences, raw strings, triple-quoted strings, and implicit concatenation. It assumes you can run Python code, call print(), and know that a name is bound to an object. Indexing, methods, and formatting come in later chapters.
What a string literal produces
Every string literal evaluates to a str object. The quotes are part of the source syntax only. They are not stored in the string.
a = 'Ada'
b = "Ada"
print(a == b)
print(type(a))
print(len(a))This prints True, <class 'str'>, and 3. The two quote styles are equivalent. The length is 3 because the quotes are not characters of the string.
Single and double quotes
Use either ' or ". Pick the one that avoids escaping the other.
print("It's fine")
print('She said "hi"')
print('It\'s also fine')The first two lines need no escapes. The third uses a backslash so that the apostrophe does not end the literal. Most style guides ask you to choose one default quote style and stay consistent. Formatters such as Black prefer double quotes.
A single-quoted or double-quoted literal must end on the line where it starts. A raw line break inside it is a SyntaxError.
Escape sequences
A backslash inside a normal literal starts an escape sequence. Python replaces the sequence with one character.
| Escape | Meaning |
|---|---|
| `\n` | Newline (line feed) |
| `\t` | Horizontal tab |
| `\\` | One backslash |
| `\'` and `\"` | Quote characters |
| `\r` | Carriage return |
| `\0` | Null character |
| `\xhh` | Character with the two-digit hex code `hh` |
| `\uXXXX` | Unicode character with a four-digit hex code |
| `\UXXXXXXXX` | Unicode character with an eight-digit hex code |
| `\N{name}` | Unicode character by its official name |
print("line1\nline2")
print("col1\tcol2")
print("back\\slash")
print("\u00e9", "\N{GREEK SMALL LETTER ALPHA}")
print(len("a\nb"))The first call prints two lines. The second separates two words with a tab. The third prints back\slash. The fourth prints é α. The last prints 3, because \n is a single character.
Unknown escapes
If a backslash is followed by a character that is not a valid escape, Python keeps the backslash. Recent versions warn about this. Python 3.12 and later raise a SyntaxWarning, and earlier versions raise a DeprecationWarning, which is hidden by default.
print("C:\temp")
print("C:\\temp")The first line is a bug. \t is a tab, so the output is C: followed by a tab and emp. The second line is correct and prints C:\temp.
Raw strings
Put r before the opening quote to get a raw string. Python then treats backslashes as ordinary characters.
path = r"C:\temp\new"
print(path)
print(len(path))This prints C:\temp\new and 11. Without the r, \t and \n would become a tab and a newline.
Raw strings are common for Windows paths and regular expressions, where backslashes are frequent.
import re
pattern = r"\d+\.\d+"
print(re.findall(pattern, "pi is 3.14, e is 2.71"))This prints ['3.14', '2.71'].
Limits of raw strings
A raw string cannot end with an odd number of backslashes. The backslash still protects the closing quote in the source, even though it stays in the value.
print(r"abc\\")
print(r"it\'s")The first line prints abc\\, with both backslashes, because a raw string does not collapse them. The second prints it\'s, with the backslash kept. A literal like r"abc\" is a SyntaxError because the quote is treated as escaped and the string never closes. To end a path with a backslash, use concatenation: r"C:\temp" + "\\".
A raw string is not a different type. It is only a different way of writing a str.
print(r"\n" == "\\n")This prints True.
Triple-quoted strings
Three quotes of the same kind, ''' or """, start a literal that can span lines. Line breaks inside it become \n characters.
poem = """Roses are red,
Violets are blue."""
print(poem)
print(repr(poem))The repr() output is 'Roses are red,\nViolets are blue.'. Single and double quotes can appear inside without escaping, as long as three in a row do not appear.
Triple-quoted strings also hold documentation strings (docstrings). They are easy to misuse with indentation, because leading spaces on each line are part of the string.
def show():
text = """first
second"""
print(repr(text))
show()This prints 'first\n second'. The four spaces before second are in the value. If you do not want them, start the text at the left margin, use textwrap.dedent, or use implicit concatenation (below).
A backslash at the end of a line inside a triple-quoted string removes the line break.
msg = """one \
two"""
print(msg)This prints one two. A newline directly after the opening quotes is kept, so a leading \ is a common way to avoid an empty first line.
import textwrap
text = textwrap.dedent("""\
first
second
""")
print(repr(text))This prints 'first\nsecond\n'.
Implicit concatenation
Adjacent string literals are joined at compile time. Parentheses let you spread a long string over several lines without adding newlines.
message = (
"This is a long message "
"split across lines, "
"but it is one string."
)
print(message)Only literals are joined this way. Two variables side by side are a syntax error, and you need + or an f-string for them. The join adds nothing, so include the spaces yourself.
A frequent bug appears in lists. A missing comma silently merges two items.
names = [
"Ada",
"Grace"
"Alan",
]
print(names)
print(len(names))This prints ['Ada', 'GraceAlan'] and 2. The list has two items, not three, and Python reports no error.
Prefixes and combining them
A literal can carry a prefix before the opening quote. Prefixes are case-insensitive.
| Prefix | Effect |
|---|---|
| `r` | Raw string |
| `f` | Formatted string literal (covered in a later chapter) |
| `b` | Bytes literal, not a `str` (covered in the Unicode chapter) |
| `rf` or `fr` | Raw and formatted |
| `rb` or `br` | Raw bytes |
The legacy u prefix is accepted and means the same as no prefix. You cannot combine b with f or with u.
Choosing a style
Some guidelines that follow from the rules above:
- Use a raw string when the text has many backslashes, such as regular expressions and Windows paths.
- Use triple quotes when line breaks are part of the data. Use parenthesized concatenation when they are not.
- Use
\nfor a single embedded newline in a short string. - Use an escape such as
\N{...}or\u...when the character is hard to type or invisible, such as a non-breaking space.
Inspecting what you wrote
When a string looks wrong, repr() shows the exact content, including escapes. print() shows the rendered text, so a tab or newline looks like whitespace.
s = "a\tb\n"
print(s)
print(repr(s))
print(len(s))repr(s) shows 'a\tb\n', and len(s) is 4. Use repr() for debugging and print() for output.
Common errors
- An unterminated literal. Forgetting a closing quote, or ending a raw string with a single backslash, gives
SyntaxError. - A single-quoted literal that runs across a line break.
- Writing
"C:\Users\new"and getting\Uor\nerrors or a surprise newline.\Ustarts an eight-digit Unicode escape, so this line fails with aSyntaxError("truncated \UXXXXXXXX escape"). Use a raw string. - Missing commas that merge neighboring literals.
- Expecting raw strings to be a separate type.
Exercise
What do len(r"a\nb") and len("a\nb") return, and why?
Show answer
The first returns 4 and the second returns 3. In the raw string, the backslash and the n are two separate characters, so the characters are a, \, n, b. In the normal string, \n is one newline character, so the characters are a, newline, b.
Exercise
A list is written as colors = ["red", "green" "blue"]. How many items does it have, and what is the second item?
Show answer
It has two items. The second is 'greenblue', because adjacent string literals are joined at compile time and the comma after "green" is missing.
Exercise
Write a regular expression pattern for one or more digits followed by a period, in a form that does not need doubled backslashes, and name the literal type you used.
Show answer
r"\d+\." is a raw string literal. Without the r prefix, you would have to write "\\d+\\.".