13
votes

I found the following regex substitution example from the documentation for Regex. I'm a little bit confused as to what the prefix r does before the string?

re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
 ...        r'static PyObject*\npy_\1(void)\n{',
 ...        'def myfunc():')
2

2 Answers

27
votes

Placing r or R before a string literal creates what is known as a raw-string literal. Raw strings do not process escape sequences (\n, \b, etc.) and are thus commonly used for Regex patterns, which often contain a lot of \ characters.

Below is a demonstration:

>>> print('\n') # Prints a newline character


>>> print(r'\n') # Escape sequence is not processed
\n
>>> print('\b') # Prints a backspace character

>>> print(r'\b') # Escape sequence is not processed
\b
>>>

The only other option would be to double every backslash:

re.sub('def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',
 ...        'static PyObject*\\npy_\\1(void)\\n{',
 ...        'def myfunc():')

which is just tedious.

3
votes

The r means that the string is to be treated as a raw string, which means all escape codes will be ignored.

The python document says this precisely:

"String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences. "