liveBook · Manning

Escape character

As explained in The Quick Python Book, Fourth Edition

A backslash is the character used in Python string literals and regular-expression patterns to introduce escape sequences or special interpretations.

A backslash gives characters special meaning inside Python strings. Common escapes include \n for a newline, \t for a tab, \\ for one literal backslash, and \" for a quote that does not end a double-quoted string. section 4.6

Use quoting and line-breaking choices to avoid unnecessary escapes:

  • Single-quoted and double-quoted strings behave equivalently; choose the delimiter that lets the other quote appear without a backslash. section 4.6
  • Triple-quoted strings permit embedded newlines and both quote characters without backslashes. section 4.6
  • A backslash can continue a statement onto the next line, but indentation in a backslash-broken string becomes part of its value. section 8.10
  • Prefer adjacent quoted string segments for readable long strings; Python automatically concatenates string literals separated by whitespace. section 8.10

Why regular expressions need extra care

Backslashes may be interpreted twice: first by Python and then by the regular-expression engine. For example, re.compile("\\ten") passes a tab followed by "en" to the regex engine, rather than a literal backslash followed by "ten". Four backslashes, as in re.compile("\\\\ten"), produce two backslashes for the regex parser, which then represents one literal backslash. section 16.3

regexp = re.compile("\\\\ten")

Inspect the four-backslash regular-expression example to see how Python string parsing and regex parsing compose. section 16.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains common escapes, quoting alternatives, line-continuation pitfalls, and two-stage regular-expression parsing without covering raw-string syntax in detail.
Examples
Demonstrates newline, tab, quote, literal-backslash, multiline-string, continued-statement, and re.compile examples.
What it assumes
Assumes familiarity with Python strings and teaches how quoting and parsing affect backslashes.
What you can do after
Apply escape sequences in Python strings and construct literal-backslash patterns with re.compile.
How it connects
Connects escape sequences with string literals, quote delimiters, multiline strings, statement continuation, and regular expressions.

Also explained in

Compare how 3 books explain escape character →

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.