Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Raw string literal `r'...'` in Python

Use the `r` prefix to keep backslashes in a string value. This is useful for regular expressions: Python preserves the backslashes, and `re` interprets them.

Version: Python 3.12

Syntax

r'...' | r"..." | r'''...''' | r"""...""" (`R` can replace `r`; `...` stands for the literal contents.)

A raw string literal r'...' is written with r or R immediately before the opening quotes, whether single, double, or triple. It produces an ordinary str: the prefix changes how the literal is read, not the type of its value. r'\n' contains two characters, a backslash and n, while '\n' contains one newline character.

Python creates the string first, then re interprets it as a pattern. r'\d+' and '\\d+' produce the same pattern, which matches one or more decimal digits. In Python 3.12, writing '\d' without the prefix produces a SyntaxWarning: \d is valid in a regex pattern but is not a recognized Python string escape. In re.sub, a replacement string has its own rules: \g<0> in a replacement means the entire match, even when the replacement is written as a raw literal.

A backslash can stop a matching quote from closing a raw literal, but the backslash remains in the value. An odd number of consecutive backslashes immediately before the closing delimiter makes the literal invalid and causes a SyntaxError. To add a single trailing backslash, write, for example, r'text' + '\\'.

Examples

import re

print(len(r'\n'), len('\n'))
pattern = r'\d+'
print(pattern == '\\d+')
print(re.sub(pattern, r'[\g<0>]', 'A12 B3'))

Result

2 1
True
A[12] B[3]

The first line shows the two string lengths, the second confirms that the pattern strings are equal, and the third shows `re.sub` wrapping each run of digits in square brackets.

Related lessons

  • Python · Lesson 29 · Intermediate · Version: 3
  • Python · Lesson 30 · Intermediate · Version: 3
  • Python · Lesson 34 · Intermediate · Version: 3

Sources