single/double quote escape interpolation

Skip Montanaro skip at pobox.com
Mon Jul 7 21:45:42 CEST 2003


    Simon> I was just wondering why python doesn't make a distinction
    Simon> between single and double quotes - a bit like Perl does.

In most instances it's helpful because you can avoid extra escapes, e.g.:

    "why don't we drop by the pub and quaff a few?"

instead of

    'why don\'t we drop by the pub and quaff a few?'

There are also triple-quoted strings using """ and ''' as the string
delimiters.  They mostly just make it easy to create multi-line string
literals, but they can also be used to avoid backslashes:

    '''Maury said, "Why don't we drop by the pub and quaff a few?"'''

    Simon> Obviously I realise there are no dollar signs so you can't
    Simon> intrpolate a varaible in a string.

You can interpret variables, the mechanism is just slightly different:

    "why don't we drop by the $where and $dowhat a few?"

for Perl, vs.

    "why don't we drop by the %(where)s and %(dowhat)s a few?" % somedict

for Python.  Somedict is a dictionary having keys "where" and "dowhat" (at
minimum).  The most common "somedict"s are probably "locals()" and
"globals()" though you can easily construct your own or take them from
different contexts, like SQL query results.

    Simon> This is fine, but having to remember to put an r in front of
    Simon> regex's is really annoying and it would be great if you could
    Simon> jsut use single quotes instead to interpolate slashes properly
    Simon> etc. (ie only escape them once).

I find having to run to the Camel book every other day more annoying. ;-) I
can never remember what all the qx, qw, etc stuff means.

Skip





More information about the Python-list mailing list