Sub topic 2
Escape sequences, raw strings, and multi-line text
This chapter assumes you can run a Python script, know the basic types str, int and float, and have used print() with simple strings. It covers three ways to control what characters end up in a string: escape sequences, raw strings, and triple-quoted strings.
Escape sequences
An escape sequence is a backslash followed by one or more characters. Python replaces it with a single character when it reads the string literal. The backslash tells Python that the next character has a special meaning.
| Sequence | Meaning |
|---|---|
| `\n` | Newline |
| `\t` | Tab |
| `\\` | One literal backslash |
| `\'` | Single quote |
| `\"` | Double quote |
| `\u00e9` | Unicode character by 4-digit hex code (é) |
print("Name:\tAda\nRole:\tEngineer")
print("She said \"hello\" and left.")
print("C:\\Users\\ada")
print("Caf\u00e9")The first line prints two lines with a tab between label and value. The other lines show an escaped quote, escaped backslashes, and a Unicode character.
You can often avoid quote escapes by choosing the other quote style:
print('She said "hello" and left.')
print("It's fine.")Raw strings
A raw string has the prefix r before the opening quote. Python keeps every backslash as a literal character and does not process escape sequences.
path = r"C:\new\table"
print(path)
print(len(path))This prints C:\new\table and 13. Without the r, \n would become a newline and \t a tab, which would corrupt the path.
Raw strings are most useful for Windows paths and regular expressions, where backslashes are common.
import re
pattern = r"\d+\.\d+"
print(re.findall(pattern, "pi is 3.14, e is 2.71"))This prints ['3.14', '2.71'].
Two limits apply to raw strings:
- A raw string cannot end with a single backslash.
r"C:\temp\"is a syntax error, because the backslash still escapes the closing quote. Write"C:\\temp\\"orr"C:\temp" + "\\"instead. - A raw string does not stop you from using
\"to include a quote, but the backslash stays in the result.
Multi-line text
A triple-quoted string starts and ends with three quotes (""" or '''). It can span several lines, and the line breaks become \n characters in the string. Escape sequences still work inside it unless you add the r prefix.
message = """Dear Ada,
Your order has shipped.
Thanks!"""
print(message)Everything between the quotes is kept exactly, including indentation. Indenting the text inside a function therefore adds spaces to every line:
def banner():
return """
Welcome
Please log in
"""
print(repr(banner()))The output shows '\n Welcome\n Please log in\n ', with the leading spaces and the extra newlines. Two fixes are common.
The first is textwrap.dedent(), which removes the indentation shared by all lines. The second is implicit concatenation, where adjacent string literals inside parentheses are joined:
from textwrap import dedent
def banner():
return dedent("""\
Welcome
Please log in
""")
text = (
"Welcome\n"
"Please log in\n"
)
print(banner() == text)The backslash right after the opening quotes cancels the first newline, so the string starts with Welcome. The program prints True.
Common errors
- Forgetting that
print()adds its own newline, so a message ending in\nproduces a blank line after it. - Using a normal string for a Windows path and getting tabs or newlines in it.
- Ending a raw string with a backslash.
- Indenting a triple-quoted string and being surprised by the extra spaces.
Exercise
What does print(len(r"a\nb")) output, and why?
Show answer
It prints 4. In a raw string the backslash is kept, so the characters are a, \, n, b. In a normal string, \n would be one newline character and the length would be 3.
Exercise
Write a line of code that stores the Windows folder C:\temp\ in a variable, ending with a backslash, without a syntax error.
Show answer
folder = "C:\\temp\\" (or folder = r"C:\temp" + "\\"). A raw string cannot end with a single backslash, so either escape the backslashes in a normal string or add the final one separately.