This guide explains Raw Strings: When to Use the r Prefix through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
An r prefix creates a raw string literal that treats most backslashes literally, which is convenient for regular expressions and Windows-looking paths. A raw string cannot end in an odd number of backslashes.
When You Would Use This
Store a Windows-style path in readable form.
Step-by-Step Example
windows_path = r"C:\Projects\Logs"
print(windows_path)
print(len(windows_path))
How the Example Works
The backslashes remain literal characters instead of starting escapes such as \P. The prefix affects the way the source literal is parsed, not the underlying type.
Example Output
C:\Projects\Logs
16
Try It Yourself
Store a regular-expression pattern for a digit using a raw string.
Common Beginner Mistakes
- Believing raw strings disable every parser rule, including the closing quote.
- Ending a raw string literal with a single backslash.
- Assuming raw strings resolve path portability problems between operating systems.
Key Takeaways
- An
rprefix creates a raw string literal that treats most backslashes literally, which is convenient for regular expressions and Windows-looking paths. - The backslashes remain literal characters instead of starting escapes such as
\P. - Avoid this mistake: Believing raw strings disable every parser rule, including the closing quote.