Safe string escaping?

Bengt Richter bokr at oz.net
Tue Mar 8 03:53:36 CET 2005


On Mon, 07 Mar 2005 19:24:43 -0500, "Grant Olson" <olsongt at verizon.net> wrote:

>I have a data file that has lines like "foo\n\0" where the \n\0 is acutally
>backslash+n+backslash+0.  I.E. a repr of the string from python would be
>"foo\\n\\0".  I'm trying to convert this string into one that contains
>actual newlines and whatnot.  I feel like there has to be a better and safer
>way to do this than eval("'%s'" % "foo\\n\\0") but I'm not finding it.
>
>Any tips would be appreciated,
>
 >>> s = "foo\\n\\0"
 >>> s
 'foo\\n\\0'
 >>> list(s)
 ['f', 'o', 'o', '\\', 'n', '\\', '0']
 >>> sd = s.decode('string_escape')
 >>> sd
 'foo\n\x00'
 >>> list(sd)
 ['f', 'o', 'o', '\n', '\x00']

You could make a de-escaping utility function, e.g.,

 >>> def de_esc(s): return s.decode('string_escape')
 ...
 >>> s
 'foo\\n\\0'
 >>> de_esc(s)
 'foo\n\x00'

You might want to write a test to verify that it does what you
expect for the kind of escaped string you are using.

Regards,
Bengt Richter



More information about the Python-list mailing list