ending a string with a backslash

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Mon May 1 06:57:33 EDT 2006


John Salerno schreef:
> Edward Elliott wrote:
>> John Salerno wrote:
>>> Obviously the single backslash at the end of 'path' will cause a
>>> problem, and escaping it with a backslash seems to fix this problem, but
>>> how does escaping work when I already have it as a raw string? 
>> see the first two items here:
>> http://www.ferg.org/projects/python_gotchas.html
> 
> #2 was very helpful. But if I want to use forward slashes instead, can I 
> just replace the backslashes with them, or must I use the 
> os.path.normcase() function to do it?

You can just replace them: all internal Windows functions accept forward 
slashed instead of backslashes in path names.

I think this is also the right time to mention os.path.join. It takes 
any number of path components and joins them, taking care of placing 
path delimiters between them. That means you could have written your 
code as follows:

path = os.path.join(r'C:\Documents and Settings\John Salerno\My 
Documents\My Webs\1and1\johnjsalerno.com', subdomain)

It also handles the case where there is a trailing backslash:

  >>> os.path.join('foo', 'bar')
'foo\\bar'
  >>> os.path.join('foo\\', 'bar')
'foo\\bar'

Greatly simplifies concatenating path components IMO.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list