Loading lessons...
Escape Characters
Some characters are special inside a string. An escape character uses a backslash to say "treat the next character literally".
The classic problem
This breaks because the quotes collide:
python
txt = "We are the so-called "Vikings" from the north."
### SyntaxError
Fix it by escaping the inner quotes:
python
txt = "We are the so-called \"Vikings\" from the north."
print(txt)
We are the so-called "Vikings" from the north.
Common escape sequences
| Code | Result |
|---|---|
\\ | backslash |
\' | single quote |
\" | double quote |
` | new line |
Examples
python
print("Line1
Line2")
### prints on two lines
print("Col1\tCol2")
### tab between words
print("It\'s mine")
### It's mine
Raw strings
A raw string, prefixed with r, ignores escapes. Handy for things like Windows paths and regex:
python
print(r"C:\Users
ame")
### prints C:\Users
ame
TL;DR
- A backslash escapes the next character.
- Common escapes: newline, \t tab, \" double quote, \' single quote, \\ backslash.
- A raw string (
r"...") keeps backslashes as-is.