93

Could you tell me why '?\\\?'=='?\\\\?' gives True? That drives me crazy and I can't find a reasonable answer...

>>> list('?\\\?')
['?', '\\', '\\', '?']
>>> list('?\\\\?')
['?', '\\', '\\', '?']
8
  • 8
    The latter is not escaping anything so it ends up being escaped itself Feb 1, 2016 at 2:05
  • 1
    No need to include list() even: >>> '?\\\?' '?\\\\?'
    – daboross
    Feb 1, 2016 at 4:20
  • @PadraicCunningham It does not "end up being escaped itself". What does that even mean?
    – user253751
    Feb 1, 2016 at 21:22
  • Amusingly, the reason is that they're both equal to two backslashes :-) Feb 1, 2016 at 21:23
  • @immibis, that is exactly what is happening. Do you know the difference between repr and str? Try printing both with one backslash in the string and it might become clear Feb 1, 2016 at 21:46

5 Answers 5

85

Basically, because python is slightly lenient in backslash processing. Quoting from https://docs.python.org/2.0/ref/strings.html :

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string.

(Emphasis in the original)

Therefore, in python, it isn't that three backslashes are equal to four, it's that when you follow backslash with a character like ?, the two together come through as two characters, because \? is not a recognized escape sequence.

6
  • 6
    That's the opposite of lenient. Lenient is most everyone else's behavior of "if you backslash a character that doesn't need it, the backslash does nothing". Together with another convention (that backslashing alphanumerics may make them special, but backslashing punctuation always makes it un-special), you get the very nice property that you can safely defang a string by backslashing all punctuation, without having to know which characters are specially interpeted — a property that Python lacks.
    – hobbs
    Feb 1, 2016 at 7:08
  • 24
    No, the opposite of lenient would be to raise an error when you use an unrecognized backslash escape. (As nearly every compiled language does. Remember that Python's string processing is basically "like C, except that we don't blow up when handed invalid backslash escapes") Also, in a string whatever the language there are only two characters that need escaping - whatever you're using as the delimiter, and backslash itself. I don't understand the argument that it's difficult to remember both of those. Feb 1, 2016 at 12:14
  • @DanielMartin there are some languages where the delimiter functions as it's own escape character (e.g. 'escape''d') . You don't even have to remember other characters there!
    – SztupY
    Feb 1, 2016 at 15:37
  • 1
    Oh wait, I guess standard pascal used that system too - see nyx.net/~gthompso/self_pasc.txt Feb 1, 2016 at 16:12
  • 1
    @DanielMartin SQL too.
    – Random832
    Feb 2, 2016 at 5:30
30

This is because backslash acts as an escape character for the character(s) immediately following it, if the combination represents a valid escape sequence. The dozen or so escape sequences are listed here. They include the obvious ones such as newline \n, horizontal tab \t, carriage return \r and more obscure ones such as named unicode characters using \N{...}, e.g. \N{WAVY DASH} which represents unicode character \u3030. The key point though is that if the escape sequence is not known, the character sequence is left in the string as is.

Part of the problem might also be that the Python interpreter output is misleading you. This is because the backslashes are escaped when displayed. However, if you print those strings, you will see the extra backslashes disappear.

>>> '?\\\?'
'?\\\\?'
>>> print('?\\\?')
?\\?
>>> '?\\\?' == '?\\?'    # I don't know why you think this is True???
False
>>> '?\\\?' == r'?\\?'   # but if you use a raw string for '?\\?'
True
>>> '?\\\\?' == '?\\\?'  # this is the same string... see below
True

For your specific examples, in the first case '?\\\?', the first \ escapes the second backslash leaving a single backslash, but the third backslash remains as a backslash because \? is not a valid escape sequence. Hence the resulting string is ?\\?.

For the second case '?\\\\?', the first backslash escapes the second, and the third backslash escapes the fourth which results in the string ?\\?.

So that's why three backslashes is the same as four:

>>> '?\\\?' == '?\\\\?'
True

If you want to create a string with 3 backslashes you can escape each backslash:

>>> '?\\\\\\?'
'?\\\\\\?'
>>> print('?\\\\\\?')
?\\\?

or you might find "raw" strings more understandable:

>>> r'?\\\?'
'?\\\\\\?'
>>> print(r'?\\\?')
?\\\?

This turns of escape sequence processing for the string literal. See String Literals for more details.

1
  • You're right '?\\\?'=='?\\?' gives False, I mistyped it. That should be '?\\\?'=='?\\\\?' as the question indicates, I've corrected it.
    – kozooh
    Feb 1, 2016 at 10:11
13

Because \x in a character string, when x is not one of the special backslashable characters like n, r, t, 0, etc, evaluates to a string with a backslash and then an x.

>>> '\?'
'\\?'
1
  • This way of explaining it is a bit confusing, simply because x happens to be one of the "special backslashable characters". Aug 4, 2022 at 21:28
6

From the python lexical analysis page under string literals at: https://docs.python.org/2/reference/lexical_analysis.html

There is a table that lists all the recognized escape sequences.

\\ is an escape sequence that is === \

\? is not an escape sequence and is === \?

so '\\\\' is '\\' followed by '\\' which is '\\' (two escaped \)

and '\\\' is '\\' followed by '\' which is also '\\' (one escaped \ and one raw \)

also, it should be noted that python does not distinguish between single and double quotes surrounding a string literal, unlike some other languages.

So 'String' and "String" are the exact same thing in python, they do not affect the interpretation of escape sequences.

1

mhawke's answer pretty much covers it, I just want to restate it in a more concise form and with minimal examples that illustrate this behaviour.

I guess one thing to add is that escape processing moves from left to right, so that \n first finds the backslash and then looks for a character to escape, then finds n and escapes it; \\n finds first backslash, finds second and escapes it, then finds n and sees it as a literal n; \? finds backslash and looks for a char to escape, finds ? which cannot be escaped, and so treats \ as a literal backslash.

As mhawke noted, the key here is that interactive interpreter escapes the backslash when displaying a string. I'm guessing the reason for that is to ensure that text strings copied from interpreter into code editor are valid python strings. However, in this case this allowance for convenience causes confusion.

>>> print('\?') # \? is not a valid escape code so backslash is left as-is
\?
>>> print('\\?') # \\ is a valid escape code, resulting in a single backslash
'\?'

>>> '\?' # same as first example except that interactive interpreter escapes the backslash
\\?
>>> '\\?' # same as second example, backslash is again escaped
\\?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.