Bug or intended behavior?

Chris Angelico rosuav at gmail.com
Mon Jun 5 13:10:05 EDT 2017


On Tue, Jun 6, 2017 at 3:01 AM, Peter Pearson <pkpearson at nowhere.invalid> wrote:
> On Fri, 2 Jun 2017 10:17:05 -0700 (PDT), sean.dizazzo at gmail.com wrote:
> [snip]
>>>>> print "foo %s" % 1-2
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> TypeError: unsupported operand type(s) for -: 'str' and 'int'
>
> Others have already pointed out that you're assuming the
> wrong precedence:
>
> Say
>     "foo %s" % (1-2)
> not
>     ("foo %s" % 1) - 2
> .
>
> Personally I prefer a less compact but more explicit alternative:
>
>     "foo {}".format(1-2)

The trouble with the zen of Python is that people now use the word
"explicit" to mean "code that I like". What is more explicit here? It
uses a method call instead of an operator, but either way, it's
completely explicit that you want to populate the placeholders in a
template string.

ChrisA



More information about the Python-list mailing list