tags:

views:

100

answers:

5

Why in python I can't use:

r"c:\"
A: 

Use "c:/" or "c:\\". Raw string literals are for escaping escape-sequences, not for including literal backslashes, though they do work that way, except in this exact case.

Roger Pate
A: 

Its a known case I think, better use "c:\\" for that case.

S.Mark
but r"c:\\" is interpreted as 'c:\\\\'
Xavier Combelle
This is presumably why Mark said `"c:\\"` and not `r"c:\\"`.
Mike Graham
I must confess that I misread
Xavier Combelle
+1  A: 

From the documentation

... a raw string cannot end in a single backslash (since the backslash would escape the following quote character).

GreenMatt
+2  A: 

When a string must contain the same quote character with with it's started, escaping that character is the only available workaround -- so the design alternative was either to make raw-string literals physically unable to contain their leading quote character, or keep the "backlash escapes" convention, even in string literals, just for quote characters.

Since raw-string literals were designed for handy representation of regular expression patterns (not for DOS / Windows paths!-), and in RE patterns a trailing backslash is never necessary, the design decision was easy (based on the real use case for raw-string literals).

Alex Martelli
a good complement is this blog article http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%E2%80%94-backslashes-in-windows-filenames/
Xavier Combelle
A: 

Even with raw strings, \" causes the " not to be interpreted as the end of the string (though the backslash gets into your string), so r"foo\"bar" would be a legal string. This is convenient enough when writing regex but not great for writing paths.

This is not a big deal as most of the time you should be using os.path and other modules to deal with your paths.

Mike Graham