Chapters
Python114 chapters

StringsChapter 21 of 114

Escape Characters

Backslashes for newlines, tabs and quotes, and the raw strings that switch them off.

The backslash changes the next character

Some characters cannot be typed directly into a string. A backslash starts an escape sequence that stands in for one:

Python
print("first\nsecond")
print("name\tage")

Output

first
second
name	age

The ones worth knowing

EscapeMeans
\nnewline
\ttab
\\a single backslash
\"a double quote
\'a single quote
\uXXXXa character by its code point
Python
print("a\\b")
print("she said \"hi\"")
print("\u00e9 \u2713")

Output

a\b
she said "hi"
é ✓

Usually you can avoid escaping quotes

Since both quote styles work, pick the one you are not using inside:

Python
print('she said "hi"')
print("it's fine")

Output

she said "hi"
it's fine

repr shows the escapes

print() shows what the string means; repr() shows how you would write it. When a value looks right but behaves oddly, repr() is the first thing to reach for:

Python
value = "line\twith\ttabs\n"
print(value)
print(repr(value))

Output

line	with	tabs

'line\twith\ttabs\n'

Raw strings

Prefix with r and backslashes stay literal. This matters most for Windows paths and for regular expressions, which have their own backslash rules:

Python
print(r"C:\temp\new\table.csv")
print("C:\temp\new\table.csv")

Output

C:\temp\new\table.csv
C:	emp
ew	able.csv

The second line is what happens without the r: \t became a tab and \n became a newline, in the middle of a path.

Escapes in regular expressions

This is the main reason raw strings exist. A regex pattern often needs a literal backslash, and writing it without r means escaping every one twice:

Python
import re
print(re.findall(r"\d+", "a1 b22 c333"))

Output

['1', '22', '333']

Line continuation

A backslash at the very end of a line joins it to the next. Brackets do the same job more safely, so this is rare:

Python
total = 1 + \
        2
print(total)

Output

3

Test yourself

2 questions

Why is "C:\Users" a SyntaxError?

Show the answer

\U starts an eight-digit unicode escape — Use a raw string, double the backslash, or use forward slashes, which Windows accepts.

What does the r prefix do?

Show the answer

Stops backslashes being read as escape sequences — It is called a raw string. Regular expressions are the main reason it exists, but it does not itself make one.

Next chapter

String Methods

The methods you will actually reach for, grouped by what you want done.