doubling slashes in a string

piet at cs.uu.nl piet at cs.uu.nl
Mon Oct 9 05:34:35 EDT 2000


>>>>> "Alex Martelli" <aleaxit at yahoo.com> (AM) writes:

AM> "Joshua Muskovitz" <josh at open.com> wrote in message
AM> news:39de8a48_3 at corp.newsfeeds.com...
>> Man, I just have to say, I *love* python.  I was struggling with the
AM> 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,"\\"), "\\\\")
>> 
>> It just keeps getting better and better.  Thanks for inventing it, Guido!

AM> Fully seconded, although:

AM>     newname = oldname.split(r'\').join(r'\\')

AM> or

AM>     newname = oldname.replace(r'\', r'\\')

AM> would strike some of us as being even better yet!-)

It would strike most of us as being particularly bad, especially those who
would try it. (A string cannot end in an odd number of \, not even a raw
string). 
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list