Difference in formatting list and tuple values

Dr. Des Small des.small at bristol.ac.uk
Thu Dec 13 18:25:17 CET 2001


sag at hydrosphere.com (Sue Giller) writes:

> I am trying to format values from either a list or a tuple, and I am 
> getting the following odd (to me) behavior.   

Well, you're doing an odd (to me) thing...

> I can format the tuple 
> entry using %d, but I get an error when I use the same formatting 
> for the same data in a list.
> Why does this happen?

> >>> print "%02d" % l[:1]			# get error with list
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: an integer is required
> >>> print "%02d" % tuple(t[:1])		# cast to a tuple works ok
> 01
> 
The right hand side of the % operator must be either a tuple or a
single item.  I would probably write

print "%02d" % t[0] 

to do this, since it works for both lists and tuples.  But if you're
secretly doing something fancy like 

print len(l)*"%02d " % tuple(l)

then you will need the cast.  The only weirdness here is that % doesn't
single elements to be tuplified, which is a concession to
readability;

print "%d" % (12,)

is also legal, but a little peculiar to look at.

Des.
-- 
Dr Des Small, Scientific Programmer,
School of Mathematics, University of Bristol,
Tel: 0117 9287984



More information about the Python-list mailing list