Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: EOL while scanning string literal while using backslash escape

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
like image 612
AdjunctProfessorFalcon Avatar asked Dec 11 '22 22:12

AdjunctProfessorFalcon


2 Answers

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 \".)

like image 189
Two-Bit Alchemist Avatar answered Mar 30 '23 01:03

Two-Bit Alchemist


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.

like image 30
Naman Sogani Avatar answered Mar 30 '23 00:03

Naman Sogani