ReviseAlgo Logo

Strings

Raw Strings

Raw string literals for regex and paths

Interview: Advanced string usage

Last Updated: June 12, 2026 5 min read

Raw strings (prefixed with r or R) treat backslashes as literal characters, preventing escape sequence processing. They are essential for regular expressions and Windows file paths.

When to Use Raw Strings

  • Regular expressions: Regex patterns use backslashes extensively. Raw strings prevent double-escaping.
  • Windows file paths: r"C:\Users\name" instead of "C:\\Users\\name"
  • Any string with many backslashes: LaTeX, ASCII art, etc.

Limitations

  • Raw strings cannot end with an odd number of backslashes: r"path\" raises SyntaxError
  • You cannot have raw byte strings with Unicode escapes: rb"..." treats everything as literal bytes
  • Quote characters still need escaping in raw strings: r"He said \"hi\""

Use Cases

Regular expression patterns (always use raw strings)

Windows file paths with backslashes

Any text with literal backslashes (LaTeX, ASCII art)

Data patterns and format strings with escape characters

Common Mistakes

Not using raw strings for regex patterns (causes double-escaping bugs)

Trying to end a raw string with a single backslash (SyntaxError)

Using raw strings when you actually need escape sequences

Not knowing about pathlib.Path as a better alternative for file paths