[Python-Dev] eval and triple quoted strings

Ron Adam ron3200 at gmail.com
Mon Jun 17 23:52:48 CEST 2013



On 06/17/2013 12:04 PM, Walter Dörwald wrote:
> Making the string raw, of course turns it into:
>
>     U+0027: APOSTROPHE
>     U+0027: APOSTROPHE
>     U+0027: APOSTROPHE
>     U+005C: REVERSE SOLIDUS
>     U+0072: LATIN SMALL LETTER R
>     U+005C: REVERSE SOLIDUS
>     U+006E: LATIN SMALL LETTER N
>     U+0027: APOSTROPHE
>     U+0027: APOSTROPHE
>     U+0027: APOSTROPHE
>
> and eval()ing that does indeed give "\r\n" as expected.

You can also escape the reverse slashes in a regular string to get the same 
result.


 >>> s1 = "'''\\r\\n'''"
 >>> list(s1)
["'", "'", "'", '\\', 'r', '\\', 'n', "'", "'", "'"]

 >>> s2 = eval(s1)
 >>> list(s2)
['\r', '\n']

 >>> s3 = "'''%s'''" % s2
 >>> list(s3)
["'", "'", "'", '\r', '\n', "'", "'", "'"]

 >>> s4 = eval(s3)
 >>> list(s4)
['\n']


When a standard string literal used with eval, it's evaluated first to a 
string object in the same scope as the eval function is called from, then 
the eval function is called with that string object and it's evaluated 
again.  So it's really being parsed twice.  (That's the part that got me.)

The transformation between s1 and s2 is what Phillip is referring to, and
Guido is referring to the transformation from s2 to s4.   (s3 is needed to 
avoid the end of line error of evaluating a single quoted string with \n in 
it.)

When a sting literal is used directly with eval, it looks like it is 
evaluated from s1 to s4 in one step, but that isn't what is happening.

Cheers,  Ron


(ps: Was informed my posts where showing up twice.. hopefully I got that 
fixed now.)
















More information about the Python-Dev mailing list