RFC PEP candidate: q'<delim>'quoted<delim> ?

phil hunt philh at comuno.freeserve.co.uk
Tue Mar 12 17:18:09 EST 2002


On 3 Mar 2002 09:50:58 GMT, Bengt Richter <bokr at oz.net> wrote:
>Problem: How to put quotes around an arbitrary program text?

I assume you mean here a *Python* program.

>    assert q'<-=delim=->'content here<-=delim=-> == 'content here' # this would be true
>
>without getting an error.

Looks a bit complex. What if you have a quoted string inside a 
quoted string, e.g, you want to quote this:

   list = [1, q'|'string|, 3]

if you just choose the same dewlimiter for the next time, it fails:

   q'|'list = [1, q'|'string|, 3]|

as this would parse as the string "list = [1, q'" followed by a 
syntax error. Of course, you could choose another delimeter, but 
it'd be nice if this could be done automatically by a simple-minded
program.

Lisp is famous for being able to quote program text. The way it 
manages it is by using (...); this is possible because any brackets 
inside must match. Let's try this for Python, using {} instead of 
(), to prevent it from looking like a function call:

   list = [1, q{string}, 3]

and:

   q{list = [1, q{string}, 3]}

This works. The reason it works is that the outer '{' only tries to 
connect to the matching '}'. Inner braces are matched with 
themselves; braces inside normal strings or comments are ignored.

>Note the lack of quotes around the final delimiter string, since it itself is
>the final delimiter. This can also be used to solve the final unescaped
>backslash problem for quoting windows paths:
>
>    q'|'c:\foo\bar\|

"""c:\foo\bar\""" and r"c:\foo\bar\" work just as well.

The best solution, of course, is to not use Windows.


-- 
<"><"><"> Philip Hunt <philh at comuno.freeserve.co.uk> <"><"><">
"I would guess that he really believes whatever is politically 
advantageous for him to believe." 
                        -- Alison Brooks, referring to Michael
                              Portillo, on soc.history.what-if



More information about the Python-list mailing list