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


