0

In python print("backslash \") produces error but print("backslash \ ") doesn't produce error.

in print(backslash \") there is no space between \ and ". and this produces a SyntaxError: EOL while scanning string literal

whereas if i give a space between the \ and " , then there in no error. Why?

few more examples

print(" this is double backslash \\\sad ")

the above statement doesn't produce any error, and it generates the output as:-

this is a single backslash \\sad 

and I get the same output on writing this :-

print(" this is a single backslash \\\\sad ")

Here I have escape each \ separately, so this is working but why the previous one is working?

Amit Upadhyay
  • 7,179
  • 4
  • 43
  • 57

2 Answers2

5

The \ character is the escape sequence character. \" escapes a quote as part of the string value, rather than a delimiter that signals the start or end of a string.

By adding a space, you produced a non-existing escape sequence, and the \ is interpreted as a literal backslash instead.

See the string literals documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

A \ without a recognised escape sequence is always a plain \ however. See the documentation for recognised sequences.

Note that this also means you need to be able to escape the escape sequence; for that reason \\ produces a single backslash literal. That way you can include \\n in a string and that is interpreted as one \ character and n, while \n produces a newline character.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Because when you print("backslash \") you are escaping the last " so therefore you get an error.. more info on escape chars: https://docs.python.org/2/reference/lexical_analysis.html

Leustad
  • 375
  • 1
  • 5
  • 20
  • sorry for that part of question..!! but what's the reason for the print of \\ ? – Amit Upadhyay Oct 23 '15 at 13:55
  • 1
    a single \ escapes the character on its right. When there is a space after '\' you are escaping the space when there is no space you are escaping " character and the first " requires the closing "... make sense? – Leustad Oct 23 '15 at 14:01