From the link, the r prefix is about raw string. Actually, there are some situations that cause me very difficult to understand the r's function. Let me express my opinion:
'H:\\Education'
equals r'H:\Education'
, as r prefix means not convert characters. But, if tested in Python, 'H:\Education'
equals 'H:\\Education'
. What is the function of r here, \
equal \\
no matter there is r leading?'H:\Education'
equals 'H:\\Education'
, 'H:\Education\'
should equal 'H:\\Education\\'
or 'H:\Education\\'
or 'H:\\Education\'
, but actually, these four are not the same in Python; Why? Is it about the location of \
or \\
?r'C:\Program Files\7-Zip\7z.exe'
is right but 'C:\Program Files\7-Zip\7z.exe'
is not right?r'H:\Education\'
is wrong, why?So, sometimes r has function, sometimes not. How can I tell them and make the right choice?
The details are in the docs at String and Bytes literals. Pay particular attention to the recognized escape sequences table a few pages down. Here are some rules
\\
is converted to \
\ooo
(with o being octal digits) is converted to octalIn...
'H:\\Education'
, the double backslash is replaced with a single backslash by rule 1.'H:\Education'
, the backslash stays in the string by rule 3.'C:\Program Files\7-Zip\7z.exe'
, the \7
is converted to an octal value by rule 2.r'H:\Education\'
the final quote is escaped (meaning it is treated as part of the literal) but that means that the literal string itself is never terminated with a closing quote which is a parser error.It's something of a dark art. The reason why people double-escape all backslashes in Windows paths is that it is easy to miss which things don't change because of rule 3 verses the multiple things that do change. Your 7z
issue is a classic case. Better to double escape everything that run the risk you missed one of the rules.