doubling slashes in a string

Fredrik Lundh effbot at telia.com
Sat Oct 7 08:37:20 EDT 2000


Joshua wrote:
> Man, I just have to say, I *love* python.  I was struggling with the problem
> of how to take a pathname and double all of the backslashes in it, so that
> (for example):
> 
> c:\foo\bar\zingo.walla.walla --> c:\\foo\\bar\\zingo.walla.walla
> 
> And I was trying for figure out how to walk the character list and build a
> new string, and then it dawned on me:
> 
> newname = string.join(string.split(oldname,"\\"), "\\\\")

note that the string module contains a shortcut:

    newname = string.replace(oldname, "\\", "\\\\")

...and in 1.6/2.0, you can also do:

    newname = oldname.replace("\\", "\\\\")

Here's another way to do it:

    newname = repr(oldname)[1:-1]

</F>




More information about the Python-list mailing list