Python r Strings: Raw String Meaning, Rules, and Examples

How-to basics · Updated November 22, 2026

In Python, r at the start of a string literal marks it as a raw string: backslashes are kept as backslashes instead of usually introducing escapes such as a newline. For example, r'\n' contains two characters, a backslash and the letter n, while '\n' contains a newline.

What the r Prefix Means

The letter r, also written as R, is a prefix in Python source code. It changes how Python reads the literal between its quotation marks; it does not create a special kind of string object at runtime. After the literal has been evaluated, a raw string is an ordinary Python str, just like a string written without the prefix.

Raw string syntax is useful when the text you are writing contains many backslashes. In an ordinary string literal, a backslash can begin an escape sequence. For instance, '\n' represents a line break and '\t' represents a tab. With the r prefix, those sequences are preserved as backslash-plus-letter characters:

  • '\n' has one character: a newline.
  • r'\n' has two characters: a backslash and n.
  • r'folder\file.txt' keeps the backslash between the path components.

The prefix must appear immediately before the opening quote, with no space: r'text' is valid, while r 'text' is not raw-string syntax. The prefix is part of Python’s notation for writing a literal, not a character stored at the beginning of the string.

Why Backslashes Need Special Attention

Backslashes appear in several kinds of text, but Python also uses them to represent characters that are awkward or impossible to type directly. Common escapes include \n for a newline, \t for a tab, \\ for one literal backslash, and \' or \" for a quotation mark when needed. Consequently, an ordinary string containing a backslash may not hold the characters its source code seems to show at first glance.

For example, print('A\nB') prints A and B on separate lines because the string contains a newline. By contrast, print(r'A\nB') prints the characters A\nB on one line. This distinction matters when the backslash is data rather than an instruction to create a control character.

Some backslash sequences are not recognized escapes. Python has historically retained certain unrecognized sequences, but relying on that behavior can produce warnings and is less clear than expressing your intent directly. Use a raw literal when you want backslashes preserved, or escape each backslash in a normal literal when that better suits the context.

How Python Reads a Raw String

“Raw” is a convenient description, but it does not mean that Python skips all interpretation. The source code still has to follow string-literal rules: it needs matching delimiters, and the delimiter determines where the literal ends. The special behavior is specifically about backslashes and escape processing. A raw literal is not a way to paste arbitrary text into source code without regard for quotes or syntax.

For example, r'line one\nline two' contains a backslash followed by n; it does not contain a line break at that point. If you need actual line breaks in a multiline string, put physical line breaks inside triple quotes, as in r'''first line
second line'''
. The raw prefix keeps backslash sequences in the text, while the actual newline between the lines remains a newline.

Python still recognizes the closing quote. A backslash immediately before a quote can affect whether that quote ends the literal, and in a raw string that backslash is retained in the resulting value. This is why raw strings can represent some backslash-and-quote combinations, but they do not make quotation marks irrelevant. Pick single or double quotes to avoid unnecessary escaping where possible.

Using Raw Strings for Regular Expressions

Regular expressions are one of the most common reasons to use raw strings. The regular-expression language uses backslashes for patterns such as \d for a digit or \s for whitespace. Python string syntax also assigns meaning to some backslash sequences, so writing a regex in a normal string can require an extra layer of escaping.

For example, the pattern r'\d+' is easy to read: Python passes a backslash and d, followed by a plus sign, to the regex engine. A normal string spelling of the same pattern is '\\d+', because its doubled backslash produces one backslash in the actual string. Both can work, but raw notation often makes patterns easier to inspect.

A raw string does not make Python interpret a regular expression. The re module does that later. In a call such as re.search(r'\d+', 'Room 42'), Python first creates a string containing the pattern characters; then the regex engine treats \d+ as a digit pattern. If a regex reports an invalid pattern, adding r will not necessarily fix it—the pattern itself must still be valid for the regex engine.

Writing Windows Paths

Windows paths often contain backslashes, so raw string literals can make them clearer. For example, r'C:\Users\Mina\Documents\notes.txt' represents a path with the usual Windows separators. Without the prefix, sequences in a path could be read as escapes, or each backslash would need to be doubled, as in 'C:\\Users\\Mina\\Documents\\notes.txt'.

Raw strings only affect how a literal is written; they do not check whether a path exists, make it portable, or convert it to a platform-specific path. For code that builds or manipulates paths, Python’s pathlib module is often a better tool:

  • Use Path(r'C:\Users\Mina\Documents') / 'notes.txt' to join path components.
  • Use Path('data') / 'notes.txt' for a relative path where Python can choose the appropriate separator.
  • Use forward slashes in many Windows path strings if convenient; Windows APIs commonly accept them, though path behavior can depend on the program or context.

For a path supplied by a user or read from a file, it is already string data; adding an r prefix in your program cannot change it. Raw notation is relevant when you write the path directly as a literal in Python source.

The Trailing-Backslash Limitation

A raw string literal cannot end with an odd number of backslashes. For example, r'C:\folder\' is invalid. The final backslash would escape the closing quote while Python is parsing the source, leaving no valid end delimiter. This is a syntax rule, not a restriction on the values that Python strings can hold.

If a string needs a trailing backslash, use a normal literal with the backslash escaped, or combine a raw literal with a separate normal literal. For example, r'C:\folder' + '\\' produces C:\folder\. For filesystem paths, joining components with pathlib is usually clearer than manually adding a trailing separator. Avoid adding a slash by string concatenation unless the specific interface requires a string in that form.

Even numbers of backslashes at the end can be written because they pair up in the source, leaving the quote available to close the literal. The practical rule is simple: a raw literal may not have a final unmatched backslash immediately before its closing quote.

Combining r with Other String Prefixes

Python allows r to combine with certain other literal prefixes. An f prefix creates an f-string, where expressions inside braces are evaluated; rf and fr are both valid ways to combine raw-string behavior with f-string interpolation. For example, name = 'Mina' followed by rf'User: {name}\n' inserts the value of name but keeps the backslash and n in the literal text.

Raw f-strings are not a way to turn off f-string rules. Braces still mark expressions, and the expression inside braces must follow Python’s expression syntax. Also, raw behavior applies to the literal portions of the f-string; it does not mean that arbitrary backslash usage inside an expression is permitted.

The rb and br prefixes create raw bytes literals. A bytes literal stores byte values rather than Unicode text, so it is different from a normal str. For example, rb'\x41' contains the four ASCII characters backslash, x, 4, and 1 as bytes, while b'\x41' uses the escape to represent the byte with hexadecimal value 41. Choose a bytes literal only when an API expects bytes; for ordinary text, use a string literal.

Raw Strings Compared with Alternatives

Choose a raw literal when preserving backslashes makes the source clearer, especially for regular-expression patterns and fixed Windows-style paths. A regular string is a good choice when you need escape sequences such as newlines, or when the text contains few backslashes. You can also double backslashes in a regular string if you want explicit control without using a raw prefix.

These choices affect the source notation, not the general capabilities of the resulting string. For example, r'\n' and '\\n' produce the same two-character string, while '\n' produces a newline. You can check the difference using len() or repr(): the raw two-character version has length 2, and the newline version has length 1. repr() displays an escaped representation for readability; it does not change the value.

There is no need to use r for every string containing punctuation. If a literal has no backslashes, the prefix usually adds no benefit. Prefer the notation that makes the intended characters easiest for another reader to verify.

Common Misunderstandings

  • It does not mean “read a file literally.” The prefix changes a source-code literal, not how a file is opened or how data from a file is decoded.
  • It does not disable all string rules. Quotes still delimit the literal, and raw strings have the trailing-backslash limitation.
  • It does not automatically apply regex rules. The re module interprets a regex pattern; the r prefix only helps write its backslashes.
  • It is not a runtime conversion. You cannot put r before a variable to make its contents raw. Once a string value exists, its characters are already determined.

One especially common confusion is seeing a backslash in a string’s representation and assuming it is present as an extra character. Tools such as the interactive interpreter often display strings using a representation that escapes special characters. For instance, the displayed representation of a newline-containing string may show \n, even though the value contains one newline character. Use print(), len(), or character-by-character inspection when the distinction matters.

Frequently Asked Questions

Does r in Python stand for raw?
Yes. It is conventionally called the raw-string prefix. It tells Python’s literal syntax to preserve backslashes rather than usually treating them as escape introducers. The resulting value is still an ordinary string.

Is r'\n' the same as '\n'?
No. The raw version contains two characters, backslash and n. The ordinary version contains one newline character. They may look similar in some displays, so use len() or repr() to distinguish them.

Can a Python raw string end with a backslash?
Not as a single raw literal ending in an odd number of backslashes. Write the final backslash as an escaped character in a normal literal, concatenate a separate literal, or use a path tool such as pathlib when working with filesystem paths.

Should I use r for every regular expression?
It is a useful convention for regex patterns containing backslashes because it reduces double escaping and improves readability. It is not mandatory: a correctly escaped ordinary string also works. The regex must still follow the regular-expression syntax supported by the re module.

Does r make a string safe or prevent errors?
No. It only changes how backslashes in a literal are handled. It does not validate a path, sanitize input, escape text for HTML or SQL, or guarantee that a regex is correct. Use the right validation or escaping method for the task.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.