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
r"Cat\\'s home"
- jfs