Categories
python python-3.x

How to test if \ symbol (backslash) is in a string?

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.