Sub topic 2
Escape sequences, raw strings, and multi-line text
This chapter assumes you can run a Python script and know the basic str type. You should also be comfortable calling print(). Here you will learn how to put characters into a string literal that you can't type directly, such as a newline, a tab, or a quote that matches the string's own delimiter. You will also learn how to switch off that behavior with raw strings and how to write text that spans several lines.
What an escape sequence is
A backslash inside a normal string literal starts an escape sequence. Python's parser replaces the backslash and the characters after it with a single character. The replacement happens when the source code is read. The resulting string object contains the real character, not the backslash.
print("Name\tScore")
print("Ada\t93")
print("Line one\nLine two")
print("a\\nb")
print(len("a\nb"))The first two lines print columns separated by a tab. The third prints two lines. The fourth uses \\ to produce one literal backslash, so it prints a\nb exactly as written. The last line prints 3, because "a\nb" holds three characters: a, a newline, and b.
Common escapes
| Sequence | Produces | Typical use |
|---|---|---|
| `\n` | Newline (line feed) | Ending a line |
| `\t` | Horizontal tab | Aligning columns roughly |
| `\\` | One backslash | Paths, regular expressions |
| `\'` | Single quote | Quote inside `'...'` |
| `\"` | Double quote | Quote inside `"..."` |
| `\r` | Carriage return | Moving the cursor to the line start |
| `\xhh` | Character with two-digit hex code | `"\x41"` is `A` |
| `\uXXXX` | Unicode character, four hex digits | `"\u00e9"` is `é` |
| `\UXXXXXXXX` | Unicode character, eight hex digits | Characters beyond the basic plane |
| `\N{name}` | Unicode character by official name | `"\N{GREEK SMALL LETTER ALPHA}"` is `α` |
print("\x41 \u00e9 \N{GREEK SMALL LETTER ALPHA}")This prints A é α if your terminal can display those characters. Encodings are covered in a later chapter.
Quotes without escapes
You often don't need \' or \". Choose the delimiter that doesn't appear in the text.
print("It's easy")
print('She said "hi"')
print("She said \"hi\" and it's fine")The third line shows the case where both quote kinds appear. You must escape one of them, or use triple quotes (covered below).
Seeing escapes with repr()
print() shows the effect of an escape. repr() shows the escape itself. When you are unsure what a string holds, print its repr().
text = "col1\tcol2\n"
print(text)
print(repr(text))The second print outputs 'col1\tcol2\n' with the backslashes visible. This is the same distinction the next-but-one chapter develops under str() versus repr().
Raw strings
Prefix a literal with r and Python stops interpreting backslashes as escape starters. Every character stays as typed.
plain = "C:\temp\new"
raw = r"C:\temp\new"
print(repr(plain))
print(repr(raw))
print(len("a\nb"), len(r"a\nb"))The first repr shows 'C:\temp\new' printed with the tab and newline as \t and \n. That output looks the same as the raw version, so check the lengths. The normal string holds a tab and a newline and is 8 characters long. The raw string keeps every backslash and is 11 characters long. The last line prints 3 4, which confirms the point: in the raw literal \n is two characters.
Raw strings matter most in two places.
- Windows paths.
r"C:\Users\ada\new_notes.txt"stays correct. Withoutr,\Ustarts a Unicode escape and the literal is a syntax error. The\nin\new_noteswould also become a newline. - Regular expressions. The
remodule has its own backslash syntax, so you want Python to leave the text alone.
import re
print(re.findall(r"\d+", "a1b22c333"))This prints ['1', '22', '333'].
Raw string limits
A raw string is not a different type. r"a\nb" is an ordinary str. Only the way the literal is read differs. Three gotchas follow from that.
- A raw string can't end in an odd number of backslashes. The backslash still prevents the closing quote from ending the literal, so
r"C:\temp\"is a syntax error. Concatenate instead:r"C:\temp" + "\\". Or usepathlib.Pathand let it add separators. - A quote can still be escaped, but the backslash stays.
r"\""is a two-character string: a backslash and a double quote. - Raw does not change what
print()does. If a raw string contains a real newline character, for example from a triple-quoted literal, it still prints as a line break.
Unrecognized escapes
A backslash followed by a character that has no meaning, such as "\d", does not raise an error. Python keeps the backslash and the character. This was silent for years. Since Python 3.12, such a literal produces a SyntaxWarning, and a later version may make it an error.
pattern = "\d+"
print(pattern)This prints \d+ but may warn. The fix is r"\d+" or "\\d+". Treat this warning as a bug in your code, not noise. A string like "\b" is valid and means backspace, not a word boundary, so a regular expression written without r can silently change meaning.
Multi-line text
Python gives you several ways to write text across lines. Which one fits depends on whether the line breaks belong in the string.
flowchart TDThe diagram below summarizes the choice.
Triple-quoted strings
A string opened with """ or ''' runs until the matching closing triple quote. Newlines in the source become newline characters in the value. You can also use both single and double quotes freely inside.
poem = """Roses are "red",
it's true.
"""
print(poem, end="")
print(repr(poem))The repr shows 'Roses are "red",\nit\'s true.\n'. Note the final \n, since the closing quotes sit on their own line. Escapes still work inside triple quotes. Use r"""...""" when you need them off.
The leading newline and the backslash continuation
If you start the text on the line after the opening quotes, the string begins with a newline. A backslash at the end of a source line removes that line break from the value. This is how you avoid a blank first line.
text = """\
first
second
"""
print(repr(text))This prints 'first\nsecond\n'. Without the backslash it would start with \n.
Indentation inside functions
Triple-quoted text inside an indented function carries that indentation into the string. Use textwrap.dedent to remove the common leading whitespace.
from textwrap import dedent
def usage():
return dedent("""\
Usage: tool [options]
-h show help
-v verbose
""")
print(usage(), end="")The output is:
Usage: tool [options]
-h show help
-v verbosededent strips only whitespace common to every line, so the extra two spaces before -h and -v survive. The end="" stops print() adding a second newline after the one already in the string.
Implicit concatenation
Adjacent string literals are joined at compile time. Wrap them in parentheses to build one long line in several source lines, with no newline added.
message = (
"Loading the configuration file, "
"checking every setting, "
"and reporting any problems."
)
print(message)A frequent bug is a missing comma in a list of strings. ["a" "b"] is a list with one item, "ab", not two. If you want separate items, check your commas.
print() and line breaks
print() adds end="\n" after its output. A string containing \n already has a break, so print("a\n") leaves a blank line. Joining a list of lines with "\n".join(lines) puts breaks only between items, which often gives cleaner results than building text with +=.
lines = ["alpha", "beta", "gamma"]
print("\n".join(lines))Carriage return
\r moves the cursor back to the start of the current line without advancing. In a terminal, print("abc\rX") shows Xbc. Programs use it to redraw a progress line with end="\r". When output goes to a file or log, the \r is stored as a character and the lines pile up, so use it only for interactive output.
Escapes in f-strings
Combine the prefixes to get a raw f-string: rf"..." or fr"...". Backslashes stay literal, and {} still marks expressions. A literal brace is written as {{ or }}. Before Python 3.12, f-string expressions could not contain a backslash at all, so f"{'\n'.join(items)}" failed. Work around that by computing the value first.
items = ["x", "y"]
joined = "\n".join(items)
print(f"Items:\n{joined}")This works on every Python 3 version, so prefer it when you must support older interpreters.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: (unicode error) 'unicodeescape' codec can't decode` | `\U` or `\x` in a Windows path string | Use a raw string |
| `SyntaxError: unterminated string literal` on `r"...\"` | Raw string ends in a backslash | Concatenate `"\\"` |
| `SyntaxWarning: invalid escape sequence '\d'` | Unknown escape kept as text | Use `r"\d"` |
| Blank line after output | Value ends in `\n` and `print()` adds another | Use `end=""` or `.rstrip("\n")` |
| Unexpected leading spaces | Indented triple-quoted text | Use `textwrap.dedent` |
Exercise
What do len("a\tb") and len(r"a\tb") return, and why do they differ?
Show answer
The first returns 3 and the second returns 4. In the normal literal, \t is replaced by one tab character, giving a, tab, b. In the raw literal the backslash is kept, so the characters are a, \, t, b.
Exercise
Write a line of Python that stores the Windows path C:\data\ (with the trailing backslash) in a variable named folder, using a raw string.
Show answer
folder = r"C:\data" + "\\". A raw literal can't end in a single backslash, so the final backslash is added as a normal string. pathlib.Path(r"C:\data") is also a good option.
Exercise
A function contains return """\ followed by indented text lines and a closing """. The printed result has extra spaces at the start of every line. Which standard-library function fixes this, and what does it remove?
Show answer
textwrap.dedent. It removes the leading whitespace that is common to all lines, so relative indentation inside the text is kept.