Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 545
NemPlayer Avatar asked May 03 '17 12:05

NemPlayer


2 Answers

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.

like image 143
zwol Avatar answered Sep 22 '22 03:09

zwol


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\\':
like image 38
Arount Avatar answered Sep 24 '22 03:09

Arount