String concatenation vs. string formatting

Ben Finney ben+python at benfinney.id.au
Fri Jul 8 18:50:03 EDT 2011


John Gordon <gordon at panix.com> writes:

> I prefer this usage:
>
>   logger.error('%s could not be stored - %s' % \
>     (self.preset_file, sys.exc_info()[1]))

That can be improved by learning two things:

* The backslash-linebreak is ugly and fragile, and almost never needed,
  since Python knows to continue a statement if any bracketing syntax
  (parens, brackets, braces, triple quotes, etc.) is still open.

  So you can continue a statement over multiple lines by introducing
  some bracketing syntax at an appropriate place. In this case, you
  don't even need to add any bracketing syntax, since the function
  parens are still open.

* The ‘%’ string formatting operator is superseded in current Python
  versions by the more flexible ‘format’ method of string objects.

So:

    logger.error(
        '{0} could not be stored - {1}'.format(
        (self.preset_file, sys.exc_info()[1]))

I usually prefer to use named placeholders instead of positional, but
this duplicates your original.

-- 
 \           “We have clumsy, sputtering, inefficient brains…. It is a |
  `\     *struggle* to be rational and objective, and failures are not |
_o__) evidence for an alternative reality.” —Paul Z. Myers, 2010-10-14 |
Ben Finney



More information about the Python-list mailing list