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

后端 未结 12 1404
后悔当初
后悔当初 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 08:04

    Despite its role, even a raw string cannot end in a single backslash, because the backslash escapes the following quote character—you still must escape the surrounding quote character to embed it in the string. That is, r"...\" is not a valid string literal—a raw string cannot end in an odd number of backslashes.
    If you need to end a raw string with a single backslash, you can use two and slice off the second.

提交回复
热议问题