Lesson 21 +10 XP

Escape Characters

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:

txt = "We are the so-called "Vikings" from the north."  # SyntaxError

Fix it by escaping the inner quotes:

txt = "We are the so-called \"Vikings\" from the north."
print(txt)  # We are the so-called "Vikings" from the north.

Common escape sequences

CodeResult
\\backslash
\'single quote
\"double quote
\nnew line
\ttab
\bbackspace
\rcarriage return
\fform feed
\ooooctal value
\xhhhex value

Examples

print("Line1\nLine2")   # 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:

print(r"C:\Users\name")  # prints C:\Users\name

TL;DR

  • A backslash escapes the next character.
  • Common escapes: \n newline, \t tab, \" double quote, \' single quote, \\ backslash.
  • A raw string (r"...") keeps backslashes as-is.