Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the single backslash raw string in Python cause a syntax error?

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


In my Python 2 program I use a lot of literal strings with embedded backslashes. I could use another backslash to escape each of these backslashes (eg: "red\\blue") or use Python raw strings (eg: r"red\blue"). I have standardised on 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 backslash literal r"\" Python complains with a syntax error. The obvious workaround is to use "\\" in this case, but why is the single raw string backslash an error? Is this a bug in Python? Is there a way to code a single backslash as a raw 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 through-out the whole program, and using this "\\" in several places seems like a kludge. Using r"\\"[0] is not any better. I have also considered using a constant BACKSLASH where BACKSLASH = r"\\"[0] at the start of the program. Another kludge.

UPDATE: This error also happens when there is an odd number of backslashes at the end of a raw string. The default string scanner that is used interprets the backslash as an escape character, so that the last backslash will escape the ending quote character. It was intended that " and ' can be embedded in the string, however the resulting string will still have the backslashes inside as a plain character.

There are several questions related to this issue but none of the answers explains why the single backslash raw string is an error or how to code a single backslash as a raw string:

python replace single backslash with double backslash

can't print '\' (single backslash) in Python

Python regex to replace double backslash with single backslash

Convering double backslash to single backslash in Python 3

Why can't I end a raw string with a backslash?

Why can't Python's raw string literals end with a single backslash?

like image 276
Logic Knight Avatar asked May 17 '15 03:05

Logic Knight


1 Answers

The problem here is simple, the system assumes that the single backslash is for escaping, you are escaping your quote, otherwise you have to escape the escape char. This would happen in any environment that lets a character disable another characters function.

like image 165
Zach S. Avatar answered Oct 05 '22 18:10

Zach S.