How can I check if there is a \ (backslash) character in a string?

So, I'm trying to run this command if r"\" in text:

and it doesn't work. He thinks the whole line is a line. How to fix it?

+3


source to share


4 answers


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 "\\"

.

+6


source


Use this:

"\\"

      



That is, a cursory backslash, not an escaped quote.

+3


source


You are struggling with escape characters.

Because it \

is an escaping character that you must escape from it to represent "this character", not "what follows after the escape".

if '\\' in 'foo\\':

      

+3


source


if "\\" in text

      

It should work, you just need to avoid it

+2


source







All Articles