How can I check if there is a \ (backslash) character in a string?
Raw literals are not completely raw. The relevant paragraph of the documentation is at the very bottom of https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals , just before the next section ("Concatenating string literals") begins:
Even in the original literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example,
r"\""
- a valid string literal consisting of two characters: a backslash and a double quote;r"\"
is not a valid string literal (even a raw string cannot end with an odd number of backslashes). In particular, the original literal cannot end with a single backslash (because the backslash escapes the next quotation mark). Also note that a single backslash followed by a newline character is interpreted as the two characters as part of the literal, not as a continuation of the line.
(Emphasis in original.)
So you can write r"\\"
and get a string containing two backslashes, and you can write r"\""
and get a string containing one backslash and one double quote, but if you want the string to only contain one backslash, you can't do it with the original literal. Instead, you need to write "\\"
.
source to share