liveBook · Manning

Escape sequence

As explained in The Quick Python Book, Fourth Edition

An escape sequence is a character sequence in a string literal that represents a character or control function using a backslash-based notation.

An escape sequence is a backslash-led character sequence inside a string literal that represents a special character or control function. Common examples include \n for a newline, \t for a tab, \\ for one backslash, and \" for a double quote. Escapes let strings contain characters that would otherwise end the literal or lack a printable one-character form. section 4.6 section 6.3

Use the notation that matches the character or representation required:

  • \' and \" represent quote characters, while \\ represents a backslash. section 6.3.1
  • \n creates a newline; \r creates a carriage return; \t creates a tab; \b, \f, \v, and \a represent other control characters. section 6.3.1
  • Represent ASCII characters numerically with three-digit octal escapes such as \155 or hexadecimal escapes such as \x6D. section 6.3.2
  • Represent Unicode characters by number with \u or by name with \N{Unicode name}. section 6.3.2

Escapes at two interpretation layers

Regular expressions interpret escapes after Python interprets the string literal. To search for the literal text "\\ten", a normal Python string needs four backslashes: re.compile("\\\\ten"). With only two, Python produces one backslash, and the regular-expression engine reads \t as a tab. section 16.3

Table 6.1 Escape sequences for string and byte literals (view table figure)

Escape sequence

Character represented

\'

Single-quote character

\"

Double-quote character

\\

Backslash character

\a

Bell character

\b

Backspace character

\f

Form-feed character

\n

Newline character

\r

Carriage-return character (not the same as \n)

\t

Tab character

\v

Vertical tab character

Use the compact reference table to compare quote, control-character, newline, carriage-return, tab, and backslash escapes. section 6.3.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines basic, numeric, and Unicode forms, then explains regex double interpretation; it defers broader Unicode-system details.
Examples
Uses newlines, tabs, quotes, backslashes, ASCII codes, Unicode names, and regex patterns as concrete examples.
What you can do after
Apply escape sequences to write strings containing control characters, quotes, backslashes, ASCII characters, and Unicode characters.
How it connects
Connects escape sequences to string literals, bytes objects, Unicode, and regular expressions.

Also explained in

Compare how 6 books explain escape sequence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.