Reputation: 1840
I know this is a noob question, but new to Python and trying to understand the following:
Why does the backslash escape work without error here:
>>> print "this is \\\ a string"
this is \\ a string
But when I try:
>>> print "\\\"
I get:
SyntaxError: EOL while scanning string literal
Upvotes: 4
Views: 6242
Reputation: 90889
It is because you have three backslashes , so the first two backslash indicate an escaped backslash , and the next backslash is used to escape the quotes, and hence there are no real ending quotes for your string causing the issue.
In the first string, the third backslash does not escape anything as it appears before a space which is not a special character and hence it gets printed.
If you do -
print "\\\ "
it may work (worked for me in python 3.4)
My version -
>>> print("\\\ ")
\\
Without space -
>>> print("\\\")
File "<stdin>", line 1
print("\\\")
^
SyntaxError: EOL while scanning string literal
Upvotes: 2
Reputation: 46759
Just a further note on what has already been mentioned, each time you use a backslash it consumes the character following it. As you probably know, some have special meaning such as \t
would insert a tab character. As you've seen, \\
is designed to show the backslash.
What Python also lets you do is prefix any string with r
which is used to mean disable the escape mechanism inside the string. For example in your first example, adding the r
would display all three backslashes 'as is'.
print r"this is \\\ a string"
this is \\\ a string
But be warned, even this trick will fail if you try your second example. You still need to avoid a backslash in the last character of a string:
print r"\\\"
SyntaxError: EOL while scanning string literal
Upvotes: 2
Reputation: 949
Your first \
escapes your second \
. Now the third \
waits for escaping another character but instead gets '
and escapes it. That's why it shows this error. This is the same error you will get if you try to do this
>>> print 'abc # Line ended while scanning string
In this case
>>> print "this is \\\ a string"
The third \
gets a space character which is not a special character. Hence third \
does not escape anything and is the part of the string.
Upvotes: 3
Reputation: 1857
When you do :
print "\\\"
First \
covers the second one and third one covers the "
(quote itself). So its like python does not see the ending quotes , so you get the errror.
Upvotes: 2
Reputation: 18457
The first backslash escapes the second backslash, and the third escapes the double quote, which then fails to terminate the string. You need either print "\\\\"
or print "\\\""
, depending on what output you are actually trying to get. (The first will print \\
and the second will print \"
.)
Upvotes: 4