String handling and the percent operator

Tom Plunket gamedev at fancy.org
Fri Jul 14 19:29:37 EDT 2006


Erik Max Francis wrote:

> > For enrichment purposes, is there a way to do this sort of thing with
> > a generator?  E.g. something like:
> > 
> > def SentenceGenerator():
> >    words = ['I', 'have', 'been', 'to', 'the', 'fair']
> >    for w in words: 
> >       yield w
> > 
> > message = "%s %s %s %s"
> > 
> > print message % SentenceGenerator()
> > 
> > (I ask because the above doesn't work)?
> 
> Use tuple(SentenceGenerator()).  A generator is just another object, so 
> using it with the % operator tries to substitute it at one value.  (Even 
> with this fix, though, your message didn't have enough formatters.)

I know that the message didn't have enough formatters, that's why I
asked.  (Although I would have assumed that the generator would get
automatically converted to a sequence that was consumable by the
interpolation operator...)

When using a generator via .next(), there's no requirement that it is
used until it is exhausted.  E.g.

  def NewId():
     v = 0
     while 1:
        yield v
        v += 1

  NextId = NewId().next

  BUTTON_OK = NextId()
  BUTTON_CANCEL = NextId()
  BUTTON_YAY = NextId()

Hence my question being "something like" rather than "something
equivalent to".  Alas, little did I know that the answer I was looking
for was not even up the same path.

-tom!



More information about the Python-list mailing list