Strings

Skip Montanaro skip+dated+1011786868.9f7890 at pobox.com
Fri Jan 18 06:54:28 EST 2002


    Max> ok, i have a string like this: "C:/Programs/.../.../"
    Max> now i need to have all the "/"s to be "\"s. how can i do this

Two choices:

    1. Use the string method replace (or string.replace if you are pre-2.0):

    >>> s = "C:/Programs/.../.../"
    >>> s.replace("/", "\\")
    'C:\\Programs\\...\\...\\'

    2. Use the appropriate normpath method.  If you are on a Windows system
       I believe you can do (I can't test this):

         import os
         os.path.normpath(s)

       If you are on a non-Windows system, import ntpath or dospath
       directly:

         >>> import ntpath
         >>> ntpath.normpath(s)
         'C:\\Programs\\...\\...'
         >>> import dospath
         >>> dospath.normpath(s)
         'C:\\Programs\\.\\.'

While importing ntpath or dospath may not seem correct, it is the correct
method to manipulate foreign paths.  Similarly, Windows users wanting to
manipulate Unix paths should import posixpath directly.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list