Safe string escaping?

G

Grant Olson

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,

Grant
 
M

Michael Hoffman

Grant said:
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.

r"foo\n\0".decode("string_escape")
 
B

Bengt Richter

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.,
'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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top