Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingJuniorOccasionalPractical

What does the `r` prefix on a string literal do, and why is it commonly used with regular expressions and Windows file paths?

Answer

A raw string literal, written with an `r` prefix like `r"\d+"`, tells Python not to interpret backslash escape sequences such as `\n` or `\t`; each backslash is kept as a literal character. This matters for regular expressions, which use backslashes extensively for their own escape syntax (`\d`, `\s`, `\w`), because a normal string would require doubling every backslash (`"\\d+"`) to avoid Python's own escape processing colliding with the regex engine's escapes. It is also handy for Windows paths like `r"C:\Users\name"`, avoiding accidental escape sequences such as `\U` or `\n` inside a path.

Strong answer includes

  • r prefix disables backslash escape interpretation
  • avoids double-escaping backslashes in regex patterns
  • also convenient for Windows-style paths

Practical example

`r"C:\new_folder"` keeps the backslashes literal, while the non-raw `"C:\new_folder"` would misinterpret `\n` as a newline escape, producing `"C:" + newline + "ew_folder"`.

#strings#regex#syntax

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics