R Means ‘Raw String’
An ‘r’ before a string tells the Python interpreter to treat backslashes as a literal (raw) character. Normally, Python uses backslashes as escape characters. Prefacing the string definition with ‘r’ is a useful way to define a string where you need the backslash to be an actual backslash and not part of an escape code that means something else in the string.
1. In this example, Python will interpret each ‘\t’ found in this string as a tab. That is, the backslash+t is interpreted as an escape sequence with a special purpose.
>>> 'path\to\the\thing' 'path\to\the\thing' >>> print('path\to\the\thing') path o he hing >>>
2. By adding the leading r, Python will know that the backslashes are to be interpreted as literal characters and not escape sequences. Interestingly, note how Python represents the literal backslash–as an escape sequence of backslash + backslash.
>>> r'path\to\the\thing' 'path\\to\\the\\thing' >>> print(r'path\to\the\thing') path\to\the\thing >>>
3. This means another way to handle the literal backslash problem is to use backslash + backslash in your string definition. However, this feels like a clunkier way to define the string to me when compared to using ‘r’. Using ‘r’ makes for, I think, more readable code.
>>> 'path\\to\\the\\thing' 'path\\to\\the\\thing' >>> print('path\\to\\the\\thing') path\to\the\thing >>>
For More Information
Python 3 Reference, section 2.4.1, “String and Bytes literals”