For example, the following code will not give an error:

rs = r'Cat\'s home' 

And this code will give:

 rs = r'Cat\\'s home' 

The same, so the error will not be:

  rs = r'Cat\\\'s home' 

And this code will give:

 rs = r'Cat\\\\'s home' 

And so on...

I remember this fact, but I don’t understand why

  • you can use external quotes others: r"Cat\\'s home" - jfs

2 answers 2

The answer from @Vitalts is given about ordinary strings. In raw strings (strings intended for regular expressions), the rules for handling slashes are somewhat different.


From the Python specification :

Quotes can be escaped with a backslash for example, it is a valid literal string of two characters: a backslash and a double quotation; r "\" is not a valid literal string (even a raw string). Specifically, a raw literal can’t end in a single backslash (since the back quote would have been the following quote character).

Transfer:

Even in raw string constants, quotation marks can be escaped with a slash, but the slash remains as a result, for example, r'\'' is a valid string constant consisting of two characters: a slash and a quotation mark. r'\' is not a valid constant (even raw strings cannot end in an odd number of slashes, since the slash escapes the closing quotation mark).

In this case, despite the fact that the slash escapes quotes, it is not thrown out of the string; the same happens for a sequence of two slashes.


Thus, this answer still overlaps with the answer @Vitalts:

 r'a\' 

EOL while scanning string literal : The string did not end because the last quote is escaped and is part of the string.

 r'a\\' 

Everything is good: the line is over, as the first slash escapes the second.

 r'\\\' 

Further, by analogy ...


 r'1 \' 2' 

Everything is OK: the quote in the middle is screened.

 r'1 \\' 2' 

The first slash escaped the second, after which the line ended. Now 2' no longer refers to the string, hence the invalid syntax

  • Who cares? (added in the answer about the middle) - Zelta
  • It seems really, no. - pynix
  • Everything, I understood everything! Close the question - pynix
  • Your question, you and close. But in fact, do not close, but put a green check next to the answer. - Zelta

Because the backslash is a special character that needs to be escaped with the second backslash. A single quote, in this case, also requires shielding with a backslash (because it is used to select a string, if the string is enclosed in double quotes, then a single string does not require shielding and vice versa)

Here you are escaping a single quote with a backslash.

 rs = r'Cat\'s home' 

Here is another backslash that needs to be escaped by another.

 rs = r'Cat\\'s home' 

Here you are screened and the second slash

 rs = r'Cat\\\'s home' 

And here one more slash was added, which is also required to be screened.

 rs = r'Cat\\\\'s home' 
  • 2
    It seems that this explanation is not for raw strings - pynix