More random python observations from a perl programmer

Greg Ewing greg.ewing at compaq.com
Mon Aug 23 00:25:12 EDT 1999


Tom Christiansen wrote:
> 
> As for the tuple thing, why can I say
> 
>     print "You have $%0.2f bucks" % (4.5/100)
> 
> How is that a singleton tuple?  Don't I have to use
> a trailing comma?

The formatting operator recognises a special case:
if you give it something which isn't a tuple, it
coerces it into a 1-tuple for you. This saves you
from having to use the awkward 1-tuple syntax when 
the format string has only one % item in it.

>  It won't let me!  Why is
> 
>     print "You have $%0.2f bucks" % (4.5/100,)
> 
> illegal,

It's not illegal! It works just fine:

>>> print "You have $%0.2f bucks" % (4.5/100,)
You have $0.04 bucks

> but
> 
>     print "You have $%0.2f bucks" % ((4.5/100,) * 2)
> 
> mandatory?

No, that one doesn't work:

>>> print "You have $%0.2f bucks" % ((4.5/100,) * 2)
Traceback (innermost last):
  File "<pyshell#9>", line 1, in ?
    print "You have $%0.2f bucks" % ((4.5/100,) * 2)
TypeError: not all arguments converted

> Was this (elt,) thing just an, er, unforeseen design
> misfeature?

For what it's worth, I don't much like it either. It would
be better if tuple construction had a clear and unambiguous
syntax like list and dictionary construction. But there don't
seem to be enough kinds of brackets left over in the ascii
character set...

Greg




More information about the Python-list mailing list