Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do 3 backslashes equal 4 in a Python string?

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

>>> list('?\\\?') ['?', '\\', '\\', '?'] >>> list('?\\\\?') ['?', '\\', '\\', '?'] 
like image 775
kozooh Avatar asked Feb 01 '16 00:02

kozooh


People also ask

Why is Python adding backslashes to string?

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.

What does a backslash do in a string?

The backslash is used to escape special (unprintable) characters in string literals.

How do you pass a backslash in a string?

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.

How do you treat backslash in Python?

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.


1 Answers

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.

like image 70
Daniel Martin Avatar answered Sep 29 '22 14:09

Daniel Martin