liveBook · Manning

Raw string literal

As explained in The Quick Python Book, Fourth Edition

A raw string literal is a Python string literal in which backslashes are generally treated as literal characters rather than introducing escape sequences.

A raw string literal tells Python not to process escape sequences when it creates a string. Put `r` immediately before the opening quote: `r"\t"` contains a backslash and `t`, rather than a tab. A raw string is still an ordinary string; only the way it is written changes. section 16.3.1

Two practical rules:

  • Use `r` or `R` with single, double, or triple quotes. A prefix makes no visible difference when the string contains no escape sequences. section 16.3.1
  • For a regular expression, raw notation leaves backslashes for the regex engine to interpret. It prevents Python’s string processing from interpreting them first; it does not disable regex special sequences. section 16.3 section 16.3.1
r"Hello" == "Hello"
 
True
 
r"\the" == "\\the"
 
True
 
r"\the" == "\the"
 
False
 
print(r"\the")
 
\the
 
print("\the")
 
        he

Compare the equality checks and printed output: raw `\t` stays as two characters, while the ordinary string begins with a tab. section 16.3.1

Writing Python code into a module file

If a triple-quoted string contains module code with `"\n"`, an ordinary outer string turns that sequence into a newline before the code is written. Prefix the outer triple quotes with `r`, as in `f.write(r"""...""")`, to preserve the code’s backslash and `n`. This fixes the premature substitution, not unrelated errors in the generated module. section 10.8.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains prefix syntax, quoting options, string comparisons, and two-stage regex interpretation, without detailing every raw-string edge case.
Examples
Contrasts printed raw and ordinary strings, compiles a regex matching a literal backslash, and repairs a generated module.
What it assumes
Builds on Python string literals and introduces the interaction between string escapes and regex escapes through examples.
What you can do after
Apply it via Python’s `re` module to write patterns without extra string-level escaping, or preserve backslashes in generated code.
How it connects
Connects string escape sequences to regular expressions, the `re` module, triple-quoted strings, and generated Python modules.

Also explained in

Compare how 3 books explain raw string literal →

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.