Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Python raw string literals: the r prefix

The `r` prefix preserves backslashes in a `str` literal. This makes regular-expression patterns easier to read without changing how `re` interprets them.

Version: Python 3.12

Syntax

r"...", r'...', R"...", R'...'; triple-quoted forms: r"""...""" and r'''...''' (also with uppercase R)

A raw string r"..." is a string literal with r or R immediately before the opening quote. Single, double, and triple quotes are allowed. The result is still a regular str: r"\n" contains two characters, a backslash and n, whereas "\n" contains one newline character.

Python builds the string first; then re interprets it as a pattern. So r"\d+" matches one or more Unicode decimal digits, not the literal text \d+. The ordinary literal "\\d+" produces the same pattern. In Python 3.12, writing "\d+" with a single backslash produces a SyntaxWarning because \d is not a recognized Python string escape.

A backslash can keep a matching quote from closing the literal, but that backslash stays in the result. An odd number of backslashes immediately before the closing delimiter is invalid and causes a SyntaxError. The r prefix only affects source-code literals; to match text received at runtime literally as part of a pattern, use re.escape(text).

Examples

import re

pattern = r"item-\d+"
print(len(r"\n"), len("\n"))
print(pattern == "item-\\d+")
print(re.fullmatch(pattern, "item-42") is not None)
print(re.fullmatch(pattern, "item-42x") is not None)

Result

2 1
True
True
False

The first line compares the literal lengths, and the second confirms that the patterns are equal. `re.fullmatch` checks the whole string: `item-42` matches, but `item-42x` does not.

Related lessons

  • Python · Lesson 34 · Advanced · Version: 5

Sources