C.W.K.
Stream
Lesson 04 of 10 · published

Python Raw Strings — Why r'\d+'

~6 min · python, strings, escape

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The double-escape problem

In Python strings, the backslash \ is the escape character. '\n' is a newline; '\t' is a tab; '\b' is the ASCII bell.

In regex patterns, the backslash is ALSO the escape character. \d is a digit; \b is a word boundary; \. is a literal dot.

Without raw strings, you'd have to write '\\d' for the regex digit class — one backslash for Python's string parser, another for regex. Annoying and error-prone.

Raw strings disable Python's interpretation

Prefix a string literal with r: r'\d+'. Now Python doesn't interpret backslashes — they pass through to regex unchanged. r'\b\w+\b' means exactly what it looks like.

The bug class without raw strings

'\b' in Python is the ASCII bell character (chr(8)). If you write re.search('\bword', text), Python sees '\x08word' as the pattern — definitely not what you wanted. Some patterns happen to work without raw strings ('\d' isn't a valid Python escape so it stays as two chars), but relying on this is fragile.

Always use raw strings for regex patterns in Python. No exceptions.

F-strings for dynamic patterns

To interpolate variables, combine raw and f-string: rf'\b{word}\b'. Or use re.escape when interpolating user input: rf'\b{re.escape(word)}\b'.

Code

Raw strings save you·python
import re

# Without raw — Python interprets \b as bell
bool(re.search('\bword', 'a word here'))   # False (probably wrong!)
bool(re.search(r'\bword', 'a word here'))  # True

# Raw + f-string for variable interpolation
name = 'pippa'
pattern = rf'\b{name}\b'  # r'\bpippa\b'
bool(re.search(pattern, 'hi pippa'))  # True

# When interpolating UNTRUSTED input, escape it
user_query = 'foo.bar'  # the user typed a literal string
safe = re.escape(user_query)  # 'foo\\.bar'
pattern = rf'\b{safe}\b'
bool(re.search(pattern, 'we found foo.bar in the data'))  # True

# Raw strings can't end in odd number of backslashes — Python quirk
# r'\\' is fine (2 backslashes)
# r'\' is a SyntaxError
# Workaround: '\\' (escaped) or r'\\' followed by literal

External links

Exercise

Run print('\b') and print(r'\b') in Python. Notice the difference. Now write a small script that searches for '\bcat\b' (no r-prefix) and explain why it doesn't find 'cat' in 'a cat sat'.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.