So I am trying to run this command if r"\" in text:
and it doesn't work. It thinks the whole line is a string. How do I fix this?
Raw literals aren't completely raw. The relevant paragraph of 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 ("String literal concatenation") begins:
Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example,
r"\""
is 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 in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.
(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 character, but if you want a string containing just one backslash, you can't do it with a raw literal. You need to write "\\"
instead.
You are struggling with the escaping characters.
Because \
is an escaping character you have to escape it to mean "this character" and not "what following will be escaped".
if '\\' in 'foo\\':
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With