[Tutor] modulus
Steven D'Aprano
steve at pearwood.info
Wed Nov 16 23:04:54 CET 2011
Wayne Werner wrote:
> On Wed, Nov 16, 2011 at 10:09 AM, Steven D'Aprano <steve at pearwood.info>wrote:
>
>> Wayne Werner wrote:
>> <snip>
>>
>>> In old style formatting, you use a string with format specifiers (%s, %d,
>>> etc.) followed by a tuple of arguments. Here, the lengths have to match
>>> exactly - if you have one specifier then you must have a 1-element tuple.
>>>
>> That's actually wrong. If you have one specifier, you must have one object
>> of any sort *except* a tuple.
>
>
> I think you misunderstood - I said a 1-element tuple - e.g. (3,)
Actually, I didn't misunderstand... I just worded my reply badly. Sorry
for the confusion.
What I should have said was, you *can* use a 1-element tuple, but you
don't *need* to use a 1-element tuple UNLESS that element is itself a
tuple. For any other object, just use the object itself. There's no need
to wrap it in a tuple first.
> As above, that's a two-element tuple. It was explained to me once that in
> this case:
>
> "%s" % 42
>
> That since python expects to see a single-element tuple it treats it as or
> converts 42 to a single element tuple.
"Treats as" may be true; "converts to" not so much. What it actually
does is this:
py> import dis
py> dis.dis(compile('"%s" % x', '', 'single'))
1 0 LOAD_CONST 0 ('%s')
3 LOAD_NAME 0 (x)
6 BINARY_MODULO
7 PRINT_EXPR
8 LOAD_CONST 1 (None)
11 RETURN_VALUE
Notice that the call to BINARY_MODULO (the % operator) takes two
arguments, the string "%s" and the object x, whatever it happens to be.
Python can't convert x to a tuple at this point, because it doesn't know
what x is, and it may not know how many format specifiers are in the
string either.
Once the string and the object hit BINARY_MODULO, all bets are off. It
will do whatever it likes, because that's purely internal implementation.
--
Steven
More information about the Tutor
mailing list