1

I am unable to understand the following results:

>>> a='\'
  File "<stdin>", line 1
    a='\'
        ^
SyntaxError: EOL while scanning string literal


>>> a=r'\'
  File "<stdin>", line 1
    a=r'\'
         ^
SyntaxError: EOL while scanning string literal

I understood that the prefix 'r' will make the string raw and \ would be treated as a normal character because r'\n' are two characters and I just removed one character from it.

>>> a='\\'
>>> a
'\\'
>>> print a
\
>>> repr(a)
"'\\\\'"

My understanding: a='\\' results in a string which actually contains a single \ while the other is just used to escape it. Cant understand why repr(a) results in so many backslashes.

>>> a=r'\\'
>>> a
'\\\\'
>>> print a
\\
>>> repr(a)
"'\\\\\\\\'"

My understanding: a=r'\\' is a string with two actual \s and each of which is prefixed with a \ to represent it as a python string. Cant understand why simply writing a on interpreter returns 4 \s and repr(a) returns 8 \s.

shiva
  • 2,535
  • 2
  • 18
  • 32

2 Answers2

1
SyntaxError: EOL while scanning string literal

The handling for a raw string is performed after the string is lexed. Since '\' cannot be lexed validly it cannot be used as part of a raw string.

>>> repr(a)

repr() doubles backslashes in the string it returns. Since you are now displaying the representation of a representation the backslashes are quadrupled.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

You are right. prefix 'r' will make the string raw. But '\' is the only exception.

repr 'Return the canonical string representation of the object.'

Nur
  • 21
  • 1
  • 4