[Tutor] double backslash in Windows paths

Lloyd Kvam pythonTutor at venix.com
Fri Apr 30 20:00:55 EDT 2004


>>> x = r'\a\b\c\d\e'
>>> x
'\\a\\b\\c\\d\\e'
>>> print x
\a\b\c\d\e
>>> repr(x)
"'\\\\a\\\\b\\\\c\\\\d\\\\e'"
>>> str(x)
'\\a\\b\\c\\d\\e'

The doubled backslashes are a convention for Python string literals. 
They are NOT actually part of the string.  normpath will give you
exactly what you really want.

The problem comes from the grief you (and Python) go through when
interpreting string literals for evaluation into the desired internal
string.  As you can see from the above examples, it can be pretty tricky
to relate the actual contents of a string that contains backslashes and
the way the string gets displayed.  x is initialized with single back
slashes just the way you would want for DOS paths.  x is never changed. 
All of the various appearances come from different display options that
are available in Python.

On Fri, 2004-04-30 at 19:21, tpc at csua.berkeley.edu wrote:
> hi everybody, what do you guys use to convert a Windows path, with single
> backslash, to double backslash ?  I ask this because I've been using
> os.path.normpath, and it leaves A LOT to be desired.  If you pass it a
> path, and say some directory in the path starts with a number,
> os.path.normpath WILL mangle the path by inserting a '\x{hex value}'
> instead of the desired behavior, '\\{dirname}'.  Then you have to go back
> and clean up and add in the extra backslash in the string before using it.
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list