Why does this (not) work?

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Tue Aug 19 20:04:19 EDT 2003


On Tue, 19 Aug 2003 19:16:27 -0400, Michael C. Neel wrote:
> why is the % operator used both for string formatting and remainders?

Historical.  Neither operation has an obvious character on the keyboard,
and the '%' did not already have an obvious application as an operator
for either strings nor numbers.

For numbers, I believe the '%' for modulus has been around at least as
early as C, probably in much earlier languages.  Its visual similarity
to the division operator, which is strongly related to modulus, probably
helped the decision.

For strings, the C printf formatting codes use '%' as a format marker
within the string, so when Python adopted the same convention, it was a
good choice when Python needed to choose a character for the operator.

> >>>"%d" % 2 * 3
> "222"
> 
> Is not what I expected nor wanted.  I could however be alone in that
> opinion.

No, you're not alone in that -- I'd certainly expect the "2 * 3" to have
a tighter binding than, and to be evaluated before, the string
formatting.

I think it's even potentially a bug that the "2 * 3" is interpreted as a
string operation, since its arguments are clearly numeric.

However, this does reinforce a principle I learned from somewhere (maybe
Scott Meyers, maybe Steve McConnell, maybe someone else) with regard to
remembering operator precedence in different languages:

Addition and subtraction are equal precedence.  Multiplication and
division are equal precedence.  Use parentheses to make explicit any
other precedence assumptions.

Using that rule, your example becomes:

    >>> "%d" % ( 2 * 3 )
    '6'

No problem.


> It's probably not hard to guess I don't like ', '.join(list) either
> ;-)

Nor I.  But I am finding the reminder of the immutability of the list to
be useful.

-- 
 \     "What if the Hokey Pokey IS what it's all about?"  -- Anonymous |
  `\                                                                   |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>




More information about the Python-list mailing list