What's the Scoop on \\ for Paths? (Win)

Steve Holden steve at holdenweb.com
Sun Jan 31 14:54:45 EST 2010


W. eWatson wrote:
> Steve Holden wrote:
> 
>> You need to read up on string literals is all. "\\" is simply the
>> literal representation of a string containing a single backslash. This
>> comes about because string literals are allowed to contain special
>> "escape sequences" which are introduced by a backslash; since this gives
>> the backslash a special meaning in string literals we also have to use
>> an escape sequence ("\\") to represent a backslash.
>>
>> In practice you will find that
>>
>> a) Many Windows APIs (but not the command line) are just as happy with a
>> forward slash as a backslash to separate file path components; and
>>
>> b) The best practice is to build filenames using the routines provided
>> in the os.path module, which guarantees to give results correct for the
>> current platform.
>>
>> regards
>>  Steve
> Basic sys functions brought out the \ separator for paths.
> 
> What am I missing here? Looks OK to me.
> 
> 
>>>> abc=r'xyz\\'
>>>> abc
> 'xyz\\\\'
>>>> print abc
> xyz\\
>>>> abc.replace(r'\',r'z')
>     
> SyntaxError: invalid syntax
>>>> abc
> 'xyz\\\\'

The SyntaxError is thrown because although backslashes lose their
special "escape sequence" meaning, for some reason I have never really
understood they retain the requirement that they be followed by another
character.

abc.replace("\\", 'z')

would have worked fine.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list