From: Niklas Norrthon on 8 Sep 2009 02:27 On 8 Sep, 05:39, Steven D'Aprano <ste...(a)REMOVE.THIS.cybersource.com.au> wrote: > On Mon, 07 Sep 2009 01:54:09 -0700, Niklas Norrthon wrote: > > Others have answered how to replace '\\n' with '\n'. For a more general > > approach which will handle all string escape sequences allowed in python > > (including '\xdd' and similar), python's eval can be used: > > eval can do so much more than handle escape sequences: Yes, eval is really cool :-) > quoted_string = ') or __import__("os").system("echo \'Pwn3d\';#rm -rf /"' > print eval('str(%s)' % quoted_string) > > Every (bad) programmer should pass untrusted strings to eval as a quick > and unsafe way to do trivial transformations. It all depends on the origin of the strings of course. I must admit that I didn't think of str.decode('string_escape') which of course is the "correct" way to solve the problem (after inspecting a sample of the input data to make sure it conforms to the specification, and isn't rtf or some such). I probably should decrease the volume of quick and dirty one time hacks I produce... /Niklas
From: Scott David Daniels on 8 Sep 2009 16:26
D'Arcy J.M. Cain wrote: > On Mon, 7 Sep 2009 15:29:23 +1000 > "jwither" <jwither(a)sxder4kmju.com> wrote: >> Given a string (read from a file) which contains raw escape sequences, >> (specifically, slash n), what is the best way to convert that to a parsed >> string, where the escape sequence has been replaced (specifically, by a >> NEWLINE token)? > > I don't know what your actual requirement is but maybe this fits: > > exec("print '%s'" % x) Lots of fun when preceded by: x = "'; sys.exit(); print 'b" or far nastier things. Exec is the same level of dangerous as eval. --Scott David Daniels Scott.Daniels(a)Acm.Org |