[Tutor] What does "TypeError: 'int' object is not iterable" mean?

Steven D'Aprano steve at pearwood.info
Sat Oct 23 13:20:53 CEST 2010


On Sat, 23 Oct 2010 09:43:07 pm Dave Angel wrote:
> On 2:59 PM, Richard D. Moores wrote:
[...]
> >> float2n_decimals(x, 3)
> >>
> >> is better written in place as:
> >>
> >> "%.*f" % (3, x)
> >>
> >> There's no need for a function for something so simple.
> >
> > Yes, but I needed one for ("%%.%sf" % n) % floatt .
> >
> > <snip>
>
> Sometimes Steven's style can be a bit caustic, 

I admit that I'm inordinately fond of sarcasm when people write posts 
saying "it doesn't work" without any further information, but what did 
I say that was caustic in this case? "There's no need for a function 
for something so simple" isn't caustic. Or sarcastic. Or nasty in any 
way.


> but there's almost 
> always a few important nuggets.  In this case, you missed the one
> that your formatting is unnecessarily complicated, at least if you
> have a recent enough Python version.
>
> In particular,
>       "%.*f" % (n, myfloat)
>
> will convert myfloat to a string, and use n as the precision, just as
> your more complex expression.  The asterisk is the magic character,
> that says use n as the precision field.
>
> This syntax was available at least in 2.3, so unless you need to use
> an older version, there's not much need for the two-stage template
> system.

It would have to be a *very* old version. The use of * as the width 
parameter in format strings goes back to the Dark Ages of Python 1.5:

[steve at sylar ~]$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat 
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> "%.*f" % (3, 1.2345678)
'1.235'

I believe this is a virtual copy of string formatting from C, in which 
case it probably goes back to the 80s or even the 70s.


-- 
Steven D'Aprano


More information about the Tutor mailing list