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

后端 未结 12 1377
后悔当初
后悔当初 2020-11-22 07:37

Technically, any odd number of backslashes, as described in the documentation.

>>> r\'\\\'
  File \"\", line 1
    r\'\\\'
       ^
Syn         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 07:57

    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.

提交回复
热议问题