Back to Blog
Python

Python Raw String Literals: Syntax and Use Cases

python raw string literal: Learn how Python raw string literals treat backslashes literally, and when to use them for regex patterns, file paths, and other backslash-h...

PythonRaw StringsRegular ExpressionsEscape SequencesBackslashes
Diagram showing a Python raw string literal with backslashes treated as literal characters

A Python raw string literal is a string prefixed with r or R, such as r"..." or r'...'. It changes how backslashes are interpreted: instead of starting an escape sequence, each backslash is kept as a literal character. This behavior is central to writing regular expressions, Windows file paths, and any text that relies on backslashes. Without raw strings, you would often need to double every backslash to get the same result, which quickly becomes error-prone.

What Is a Python Raw String Literal?

A raw string literal is declared by placing an r or R immediately before the opening quote. The syntax is identical to a normal string except for the prefix. For example:

path = r"C:\Users\name" pattern = r"\d+"

In both cases, the backslashes are preserved exactly as written. The r prefix does not create a different type; the result is still a str object. The only difference is the parsing rule applied when the literal is compiled.

How Backslashes Are Treated in Raw Strings

In a normal Python string, a backslash introduces an escape sequence. For instance, "\n" becomes a newline character, and "\t" becomes a tab. In a raw string, the backslash is not an escape character; it is simply a backslash. So r"\n" is two characters: a backslash followed by the letter n. This is the core behavior that makes raw strings valuable.

Consider the difference:

normal = "\n" raw = r"\n" print(len(normal)) # 1 print(len(raw)) # 2

normal contains a single newline character, while raw contains a backslash and an n. This distinction matters whenever you need to represent literal backslashes in your code.

Using Raw Strings for Regular Expressions

The most common use of raw strings is in regular expressions. The re module interprets backslashes as part of its own escape syntax, such as \d for a digit or \s for whitespace. If you write a regex pattern as a normal string, you must escape each backslash for Python's string parser first, then the regex engine sees the correct pattern. This leads to confusing double backslashes:

import re # Normal string: each backslash must be doubled pattern = "\\d+" result = re.findall(pattern, "abc123")

With a raw string, you write the pattern exactly as the regex engine expects:

pattern = r"\d+" result = re.findall(pattern, "abc123")

The raw string version is clearer and less prone to mistakes. This is why the Python documentation and most style guides recommend raw strings for all regex patterns. Even if a pattern contains no backslashes, using r is a good habit because it future-proofs the code if you later add a backslash.

Raw Strings and Windows File Paths

Windows uses backslashes in file paths, which conflicts with Python's escape sequences. For example, the path C:\Users\name contains \U and \n if written as a normal string, both of which are invalid or unintended escapes. A raw string solves this directly:

path = r"C:\Users\name" print(path) # C:\Users\name

Without raw strings, you would need to double every backslash:

path = "C:\\Users\\name"

This is tedious and easy to get wrong. Raw strings are the natural choice for Windows paths, though you should be aware that they cannot end with a backslash, as explained in the next section.

Common Pitfalls and Edge Cases

Raw strings have a few quirks that can surprise developers. The most notable is that a raw string cannot end with an odd number of backslashes. Because the backslash still quotes the following character, a trailing backslash escapes the closing quote, leaving the string unterminated. For example, r"C:\" is a syntax error. To represent a path that ends with a backslash, you must either use a normal string with doubled backslashes or append the backslash separately:

# Invalid: r"C:\" # Valid alternatives: path1 = "C:\\" path2 = r"C:" + "\\"

Another edge case is that raw strings still treat quotes as delimiters. To include a quote inside a raw string, you can use the opposite quote type or escape it with a backslash, but the backslash remains in the string. For instance:

s1 = r'He said "hello"' s2 = r"She said \'hi\'"

In s2, the backslashes are literal, so the string contains She said \'hi\' rather than She said 'hi'. This is rarely what you want, so it's usually cleaner to use the opposite quote style.

When Not to Use a Raw String

Raw strings are not appropriate when you actually need escape sequences. For example, if you want a string containing a newline, you must use a normal string: "\n" gives a newline, while r"\n" gives a backslash and an n. Similarly, if you need a tab, a Unicode escape, or any other escape sequence, a raw string will not process it. The r prefix only affects backslash handling; it does not change any other string behavior.

A common mistake is to use raw strings for all strings in a program, which breaks text that relies on newlines or tabs. Reserve raw strings for cases where backslashes are literal, such as regex patterns and Windows paths.

Raw Strings and Unicode Escapes

In Python 3, raw strings also disable Unicode escapes. A normal string like "\u0041" is interpreted as the character A. A raw string r"\u0041" is the literal text \u0041—six characters: backslash, u, 0, 0, 4, 1. This behavior is consistent with the general rule that backslashes are literal, but it can be surprising if you expect Unicode handling. If you need to combine raw string behavior with Unicode escapes, you cannot do so directly; you must use a normal string or concatenate the Unicode character separately.

Practical Recommendations for Using Raw Strings

When writing code that involves backslashes, raw strings improve readability and reduce the chance of errors. For regular expressions, always use r even if the pattern currently has no backslashes—it costs nothing and prevents future mistakes. For Windows paths, raw strings are the standard choice, but remember the trailing-backslash limitation. For any other string that needs escape sequences, stick with normal strings. By applying these rules, you keep your code clear and maintainable without fighting Python's escape rules.

python raw string literal: Practical Usage and Code Examples | RYUSLOG DEV