Why can’t Python’s raw string literals end with a single backslash?

The whole misconception about python’s raw strings is that most of people think that backslash (within a raw string) is just a regular character as all others. It is NOT. The key to understand is this python’s tutorial sequence:

When an ‘r‘ or ‘R‘ prefix is present, a character following a
backslash is included in the string without change, and all
backslashes are left in the string

So any character following a backslash is part of raw string. Once parser enters a raw string (non Unicode one) and encounters a backslash it knows there are 2 characters (a backslash and a char following it).

This way:

r’abc\d’ comprises a, b, c, \, d

r’abc\’d’ comprises a, b, c, \, ‘, d

r’abc\” comprises a, b, c, \, ‘

and:

r’abc\’ comprises a, b, c, \, ‘ but there is no terminating quote now.

Last case shows that according to documentation now a parser cannot find closing quote as the last quote you see above is part of the string i.e. backslash cannot be last here as it will ‘devour’ string closing char.

Leave a Comment