Why does print("\"+"addplot [boxplot]") yield a syntax error?

Viewed 19

Apologies for the very simple question; I myself am surprised I could be stumped by a 1-line program containing nothing more complicated than a string in a print command.

I just want Python to print the following line:

\addplot [boxplot]

First I tried

print("\addplot [boxplot]")

but that made it print

 ddplot [boxplot]

I reasoned this must be because the forward slash is a special symbol in a string; so I tried isolating it: print("\"+"addplot [boxplot]"). But that gives me a SyntaxError, with the pointer on the t in addplot. Why is that?

Edit: Ok, after some reading, the basic problem is that \" is interpreted as the right quotation marks being part of the string, and then the right quotation marks are no longer available to close the first part of the string (intended to contain just the backslash).

One can try to fix it by typing r"\" instead, which makes Python consider the backslash as part of the string. But this doesn't work either for reasons explained in Why can't Python's raw string literals end with a single backslash?.

The correct answer is to have "\\" instead. It's kind of awkward because elsewhere I print double backslashes. But it works, the reason being that the first backslash signals to include the second as part of the string.

I'm not sure why the comment mentions forward slashes, as that isn't what I'm trying to print. But ok, this is enough to close the question. Sorry for the bad question.

0 Answers
Related