Could you tell me why '?\\\?'=='?\\\\?'
gives True
? That drives me crazy and I can't find a reasonable answer...
>>> list('?\\\?') ['?', '\\', '\\', '?'] >>> list('?\\\\?') ['?', '\\', '\\', '?']
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.
The backslash is used to escape special (unprintable) characters in string literals.
string = string. split("\\"); In JavaScript, the backslash is used to escape special characters, such as newlines ( \n ). If you want to use a literal backslash, a double backslash has to be used.
Use the Python backslash ( \ ) to escape other special characters in a string. F-strings cannot contains the backslash a part of expression inside the curly braces {} . Raw strings treat the backslash (\) as a literal character.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With