regular expression conundrum

Bengt Richter bokr at
Wed Aug 14 23:10:40 CEST 2002

On 14 Aug 2002 13:08:09 -0500, Chris Spencer <clspence at> wrote:

>	I'm building a string that will be eval()-ed.  I'm building a string
>which will include Windows path names.  Some of my users, not knowing Python,
>will do something like this: "d:\foo\bar\"+filename
>	When eval()-ed, the " is escaped by the final backslash in the directory
>string.  I'm making it easy on them by giving them an option to wholesale escape
>all backslashes.  But just in case they did it RIGHT by typing:
>"d:\foo\bar\\"+filename  I want to make sure that the final two backslashes
>aren't escaped again, causing two backslashes to be present in an eval().
I presume you just forgot the r prefix for raw string format? In any case, it is
often helpful to turn your string into a list of single characters with list(),
so you can see them unambigously when testing your program. E.g,

 >>> filename = 'xxx'
 >>> list("d:\foo\bar\\"+filename)
 ['d', ':', '\x0c', 'o', 'o', '\x08', 'a', 'r', '\\', 'x', 'x', 'x']
             ^^^^-form feed    ^^^^-back space   ^^-single backslash char

versus with the raw-string prefix:
 >>> list(r"d:\foo\bar\\"+filename)
 ['d', ':', '\\', 'f', 'o', 'o', '\\', 'b', 'a', 'r', '\\', '\\', 'x', 'x', 'x']

versus a properly escaped non-raw-string windows path
 >>> list("d:\\foo\\bar\\"+filename)
 ['d', ':', '\\', 'f', 'o', 'o', '\\', 'b', 'a', 'r', '\\', 'x', 'x', 'x']

versus the option I guess you are giving them:
 >>> list(r"d:\\foo\\bar\\"+filename)
 ['d', ':', '\\', '\\', 'f', 'o', 'o', '\\', '\\', 'b', 'a', 'r', '\\', '\\', 'x', 'x', 'x']

Bengt Richter

More information about the Python-list mailing list