[Tutor] Raw string

Steven D'Aprano steve at pearwood.info
Mon Apr 19 01:25:37 CEST 2010


On Mon, 19 Apr 2010 07:49:31 am Neven Goršić wrote:
> Hi!
>
> When I get file path from DirDialog, I get in a (path) variable.
> Sometimes that string (path) contains special escape sequences, such
> as \x, \r and so on.
>
>              'C:\Python25\Programs\rating'

That creates a string containing a \r character, which is a carriage 
return.

You could write it as a raw string

r'C:\Python25\Programs\rating'

but that will fail if the string ends with a backslash. Or you could 
escape your backslashes:

'C:\\Python25\\Programs\\rating'

The best solution is to remember that Windows will accept either 
backslash or forward slash in paths, and so write:

'C:/Python25/Programs/rating'

Another solution is to construct the path programmatically, e.g.:

parts = ['C:', 'Python25', 'Programs', 'ratings']
path = '\\'.join(parts)

but frankly I would consider any solution except "use forward slashes" 
to be a waste of time -- CPU time *and* programmer time.


> When I try to open that file (whose name contains escape sequences)
> it doesn't work.

Only because the file doesn't exist. If you actually have a file called 
Programs\rating in the C:/Python25/ directory, you will open it.




-- 
Steven D'Aprano


More information about the Tutor mailing list