[Tutor] How to replace the '\'s in a path with '/'s?
Steven D'Aprano
steve at pearwood.info
Sun Jul 31 09:29:48 CEST 2011
Sandip Bhattacharya wrote:
> Generally, converting slashes manually should be kept at a minimum. You
> should be using library functions as much as possible. The experts here
> can correct me here, but this is a roundabout way I would be doing this:
str.replace('\\', '/') is a perfectly fine library function to use to
convert backslashes.
[...]
> # Use raw strings so that backslash doesnt matter
> path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
That's not quite true. Even with raw strings, you can't write:
path = r'C:\Users\Dick\Desktop\Documents\Notes\'
Try it and see what happens.
[...]
> I am not happy with the loop to collect the components. But I couldn't
> find a single path function which splits a path into all the components
> in one go.
Just use str.split.
Be prepared to filter out empty path components if the user enters a
path with doubled-up backslashes:
C:\Users\Dick\\Desktop
but that's no real difficulty.
--
Steven
More information about the Tutor
mailing list