Python r string: how raw strings keep backslashes
Learn what the r prefix does in Python, when raw strings help with regex and Windows paths, and the trailing-backslash and quote pitfalls to avoid.
In Python, writing the letter r (or R) directly before a string literal creates a raw string. Inside it, a backslash is an ordinary character instead of the start of an escape sequence such as \n or \t. This guide covers what that changes, where it helps, and the few cases where it causes surprises.
What the r prefix does
In a normal string literal, the backslash is an escape character: "\n" becomes one newline character and "\t" becomes one tab. In a raw literal, Python keeps the backslash and the character after it exactly as you typed them. The input is the literal in your source code, and the result is an ordinary str object. There is no separate raw-string type. The prefix only changes how Python reads the literal when it parses your code.
# Example: the same characters as a normal and a raw literal
normal = "C:\new\table"
raw = r"C:\new\table"
print(len(normal)) # 10: \n and \t each became a single character
print(len(raw)) # 12: every backslash is kept
print(raw) # C:\new\table
The prefix affects only literals written in source code. Python never processes escape sequences in text that arrives at runtime. That includes text read from a file, returned by input(), loaded from a database or passed as a command-line argument. Any backslash in that text is already a literal backslash, so you cannot convert such a string to raw, and you don't need to.
Why the interpreter shows doubled backslashes
At the interactive prompt, or whenever you call repr(), Python displays a string in its escaped form, which doubles each backslash. The string itself has not changed. print() shows the actual characters, and len() confirms how many there are.
>>> path = r"C:\new"
>>> path
'C:\\new'
>>> print(path)
C:\new
>>> len(path)
6
Where raw strings help
Regular expressions
The re module has its own backslash syntax: \d matches a digit, \s matches whitespace and \b matches a word boundary. In a normal literal, Python handles backslashes before the regex engine sees them, so you would have to double every one, as in "\d+". A raw literal passes the pattern to the regex engine unchanged.
import re
text = "order 42 shipped"
# Example. Without r, "\b" is a backspace character (\x08), so nothing matches
print(re.search("\b42\b", text)) # None
# With r, \b reaches the regex engine as a word boundary
print(re.search(r"\b42\b", text)) # <re.Match object; span=(6, 8), match='42'>
Sequences such as \d are not valid Python escapes. They happen to survive in a normal literal, but Python flags them. Older 3.x releases issue a DeprecationWarning, Python 3.12 and later issue a SyntaxWarning, and the documentation says they will become errors in a future version. Writing patterns as raw strings avoids the issue entirely.
Windows file paths
Windows paths contain many backslashes, and folder names can collide with escape sequences. \n and \t are silently turned into a newline and a tab. The \U in "C:\Users" starts a Unicode escape, so a normal literal containing it fails with a SyntaxError. A raw literal keeps the path intact.
# Example
log_dir = r"C:\Users\dev\temp\new_logs"
Two alternatives avoid backslashes altogether. Windows generally accepts forward slashes in paths passed from Python. pathlib.Path can also join path parts for you, for example Path("C:/Users") / "dev" / "temp".
LaTeX and other backslash-heavy text
Markup such as LaTeX uses backslash commands that overlap with Python escapes. In "\frac{a}{b}", the \f becomes a form-feed character, while r"\frac{a}{b}" keeps the command as written. The same applies to any text you want stored exactly as typed, such as sample escaped data in tests.
Limits and surprises
A raw string cannot end in a single backslash
Inside a raw literal, a backslash still stops the next quote from closing the string, even though the backslash itself is kept. That makes r"C:\temp" a syntax error, because Python reads the final quote as part of the text and the literal never ends. More generally, a raw literal cannot end with an odd number of backslashes. Note also that r"\" is two backslash characters, not one.
# Example: two ways to get C:\temp\ with a trailing backslash
a = r"C:\temp" + "\\"
b = "C:\\temp\\"
Escaped quotes keep their backslash
For the same reason, r""" is a valid literal, but it contains two characters: a backslash and a double quote. If you only want a quote inside the text, switch quote styles, as in r'say "hi"', or use triple quotes.
Unicode and hex escapes stay literal
Python does not process escapes such as \u00e9, \x41 and \N{...} in a raw str literal, so r"\u00e9" is six characters rather than é. If you need a real Unicode escape next to literal backslashes, place a normal literal and a raw literal side by side. Python joins adjacent literals into one string.
# Example: é followed by the regex token \d+
pattern = "\u00e9" r"\d+"
Combining r with other prefixes
| Prefix | Result | Backslashes | Example |
| r or R | str | Kept literally | r"\d+" |
| rb or br, any letter case | bytes | Kept literally | rb"\x00" is four bytes, not one |
| rf or fr, any letter case | str with {} replacement fields | Kept literally; braces still interpolate, and {{ }} produce literal braces | rf"{root}\logs" |
In Python 3 the u prefix cannot be combined with r. Plain r already produces a Unicode str.
Step by step: write a raw string and check the result
- 1. Decide whether each backslash in your text should be a character (paths, regex, LaTeX) or an escape (newline, tab). Use r only when you want characters.
- 2. Put r directly before the opening quote, with no space: r"...".
- 3. Make sure the literal does not end in a single backslash. If the text must end with one, add "\" as a separate normal literal.
- 4. Check the result with print() to see the real characters and with len() to count them. Ignore the doubled backslashes that repr() shows.
- 5. For a regex, test the pattern on a known sample with re.search() or re.fullmatch() before you apply it to real data.
- 6. Skip r for text from files, user input or other runtime sources, because the prefix only applies to literals in code.
The examples here illustrate behavior described in Python's language reference. They were not captured from a specific installation. Error-message wording and warning categories differ between Python versions, so confirm details against the interpreter you use.