Use raw Python strings to express regex backslashes clearly.
How It Works
A raw string prefix r reduces Python string-literal escape processing, making patterns such as r"\d+" easier to read. Raw strings do not switch off regex escaping itself, and they cannot end with an odd number of backslashes.
Step-by-Step Example
import re
pattern = r'\d{3}-\d{2}'
print(bool(re.fullmatch(pattern, '123-45')))
print(re.findall(r'\bcat\b', 'cat scatter cat'))
Understanding the Example
- The expression "r'\\d{3}-\\d{2}'" supplies the value stored as 'pattern'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
True
['cat', 'cat']
Where This Fits in a Real Program
Before putting the technique into a larger program, identify the required inputs and which results are returned. Choose what should happen with invalid or missing data, and test a small valid case and a failing case independently.
Practice: Try It Yourself
Use re.escape() for user-provided literal text.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Thinking r-strings disable all regex escapes or writing a raw literal ending in a single backslash.
- Rewrite a pattern containing and \d using a raw string.
Key Takeaways
- Use raw Python strings to express regex backslashes clearly.
- A raw string prefix r reduces Python string-literal escape processing, making patterns such as r"\d+" easier to read.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.