Hot to split string literals that will across two or more lines ?

Fredrik Lundh fredrik at
Wed Nov 23 13:18:14 CET 2005

Magnus Lycka wrote:

> Fredrik Lundh wrote:
>>     cursor.execute(
>>         'select * from foo'
>>         ' where bar=%s'
>>         ' limit 100',
>>         bar
>>     )
> The disavantage with this is that it's easy to make
> a mistake, like this...
>      cursor.execute(
>          'select * from foo '
>          'where bar=%s'
>          'limit 100',
>          bar
>      )

that's why I prefer to put the spaces first.  if you do that, you'll spot
the mistakes immediately.

(on the other hand, the chance that the SQL engine won't notice this
typo is pretty slim).

> That might be a reason to prefer triple quoting instead:
>      cursor.execute(
>          '''select * from foo
>          where bar=%s
>          limit 100''',
>          bar
>      )

"but it looks ugly"

(as usual, threads like this goes round and round and round ;-)

> This last version will obviously contain some extra whitespace
> in the SQL text, and that could possibly have performance
> implications, but in general, I prefer to reduce the risk of
> errors (and I've made mistakes with missing spaces in adjacent
> string literals).

absolutely.  but if you don't want newlines and whitespace in your
strings, using auto-catenated plain literals is a good alternative, at
least if you combine with a little indentation discipline.


More information about the Python-list mailing list