Why is the only backslash in Python causing a syntax error?

Also see Why can't I end the raw backslash line? and Why can't Python raw string literals end with a single backslash? and relevant answers.


In my Python 2 program, I use a lot of literal strings with built-in backslashes. I could use another backslash to escape each of these backslashes (for example: "red\\blue" ) or use the original Python strings (for example: r"red\blue" ). I standardized the raw string method, which works well in all cases except one.

If I want to represent a double backslash, I can use r"\\" , but if I try to enter a single literal backslash r"\" , Python will complain about a syntax error. An obvious workaround is to use "\\" in this case, but why is the only unhandled line a reverse failed error? Is this a bug in Python? Is there a way to encode a single backslash as the source string?

Example:

 >>> r"red\blue" 'red\\blue' >>> r"\\" '\\\\' >>> r"\" File "<stdin>", line 1 r"\" ^ SyntaxError: EOL while scanning string literal >>> 

I would rather be consistent, using raw strings, across the entire program, and using this "\\" in several places seems like a clone. Using r"\\"[0] not better. I also considered using the BACKSLASH constant, where BACKSLASH = r"\\"[0] at the beginning of the program. Another kud.

UPDATE: This error also occurs when there is no even number of backslashes at the end of a line. The default line scanner interprets the backslash as an escape character, so the last backslash avoids the quote end character. It was assumed that " and ' could be embedded in a string, however the resulting string would still have a backslash inside as a simple character.

There are several questions related to this problem, but none of the answers explain why a single backslash line is an error or how to encode a single backslash as a raw string:

python will replace one backslash with a double backslash

cannot print '\' (single backslash) in Python

Python regex to replace double backslash with one backslash

Converting a double backslash to a single backslash in Python 3

Why can't I end the backslash line?

Why don't Python source string literals end in a single backslash?

+5
source share
1 answer

The problem here is simple, the system assumes that a single backslash is escaping, you avoid your quote, otherwise you need to avoid the escape char. This will happen in any environment that allows the character to disable the function of other characters.

+1
source

All Articles