Escape Key in Code

Hi. Why will the below code output 2?
The first \ symbol is considered as an escape key, so why isn’t the result = 3?
Thank you.

x = "\\\\"
print(len(x))

Case #2 : Why does the below code produce an error?

x = "\\\"
print(len(x))

I get 4. Please copy and paste your code, don’t retype it. Otherwise it’s very hard to explain what’s going on.

What error are you seeing? Both snippets run without error for me, and print 4. In both cases, x is assigned the string " \\ " (that’s ‘space’, ‘backslash’, ‘backslash’, ‘space’).

Are you using Python 3.12? Maybe you’re seeing a syntax warning due to \ being an invalid escape sequence:

SyntaxWarning: invalid escape sequence '\ '

If so, that’s a warning, not an error. Your code is still running, just with an extra diagnostic to warn you about potentially undesirable behavior.

oh okay, sorry. I have edited the original. copy pasted as is.

I have edited the original. copy pasted as is.

"\\\\" contains two escape sequences, \\ and \\. Both represent a single backslash, so you get a string with with two backslashes.

"\\\" also contains two escape sequences, \\ and \". The first represents a backslash, the second represents a double-quote. You’re then missing a closing " for the string, hence the error: SyntaxError: unterminated string literal.

See also Backslash in a string gives an error.

2 Likes

aha… i see. Thank you so much!

String literally unterminated, so why you get
an error

A question: why this output?

>>> str("\\")
'\\'
>>> repr("\\")
"'\\\\'"
>>> print("\\")
\

The first two implicitly call repr on the strings returned by str and repr, respectively, in order to show the values in the REPL.

print, on the other hand, simply writes the single character present in its argument. (The REPL declines to show the value of the expression, namely None.)

Try using print in the first two examples instead of relying on the REPL’s automatic display.

>>> print(str("\\"))
\
>>> print(repr("\\"))
'\\'

And more explicit versions of the original calls to repr and str:

>>> print(repr(str("\\")))
'\\'
>>> print(repr(repr("\\")))
"'\\\\'"
1 Like