Sub topic 10
Writing string literals
This chapter assumes you can run Python code, call print(), and know that a name is bound to an object. A string literal is text written directly in your source code. Python turns it into a str object.
Single and double quotes
Single and double quotes make the same kind of string. Pick the one that avoids escaping the other.
a = 'single'
b = "double"
c = "It's fine"
d = 'She said "hi"'
print(a, b, c, d)
print(a == "single")The last line prints True. Which quote you used leaves no trace in the object.
Escape sequences
A backslash inside a normal string starts an escape sequence. It is a short code that stands for one character that is hard to type.
| Escape | Meaning |
|---|---|
| `\n` | newline |
| `\t` | tab |
| `\\` | one backslash |
| `\'` and `\"` | a quote character |
| `\uXXXX` | Unicode character by hex code |
| `\N{name}` | Unicode character by name |
print("Line1\nLine2")
print("Col1\tCol2")
print("Quote: \" and backslash: \\")
print("\u00e9 \N{GREEK SMALL LETTER ALPHA}")The escape is one character in the string, even though you typed two or more. len("a\nb") is 3.
Raw strings
A raw string has an r before the opening quote. Python then keeps every backslash as a literal character. Raw strings suit Windows paths and regular expressions, which use many backslashes.
path = "C:\new\table"
print(path)
raw = r"C:\new\table"
print(raw)
print(len(raw))The first print shows a broken path, because \n became a newline and \t became a tab. The raw version prints C:\new\table and has length 12.
An unrecognized escape such as "\d" is not an error, but recent Python versions warn about it (a SyntaxWarning since 3.12). Use a raw string or write \\d.
Triple-quoted strings
Triple quotes, """ or ''', let a string span several lines. Each line break becomes a \n in the string. Quotes of the other kind, and single quotes of the same kind, need no escaping inside.
poem = """Roses are red,
Violets are blue."""
print(poem)
print(len(poem.splitlines()))This prints the two lines and then 2. Be careful with indentation: any spaces before the text inside the quotes become part of the string.
Adjacent literals
Literals written side by side, with only whitespace between them, join at compile time. Inside parentheses this lets you split a long string across lines.
message = (
"This is a long message "
"split across two lines."
)
print(message)Without the parentheses, a line break would end the statement. Without the trailing space inside the first literal, the words would run together.
Choosing a form
Common errors
- Forgetting a closing quote gives
SyntaxError: unterminated string literal. - Putting a raw string prefix after the quote does nothing useful. The prefix goes before the opening quote.
- Expecting
\nto work in a raw string. It stays as two characters.
Exercise
What does print(len(r"a\tb"), len("a\tb")) print, and why?
Show answer
It prints 4 3. In the raw string the backslash and t stay as two characters, so the characters are a, \, t, b. In the normal string \t is one tab character, so the characters are a, tab, b.