using generators with format strings

Hans Nowak hans at zephyrfalcon.org
Wed Jul 21 21:37:37 EDT 2004


marduk wrote:
> On Wed, 21 Jul 2004 16:38:55 -0400, brianc wrote:
> 
> 
>>List comprehension is a beautiful thing.
>>
>>x = "Hello, %s, this is a %s with %s and %s on top of %s" %
>>tuple([myvalues() for i in xrange(5)])
>>
>>You could even make the xrange argument dependent upon the
>>number of "%s" in the string. 
> 
> 
> Well, that has two problems:
> 
> a) the tuple is a list of generators of strings, not strings
> b) I was hoping I would not have to count all the "%s"s in the string

An interesting problem.  Apparently the % string interpolation operator checks 
the length of the tuple, so you cannot use an object (generator or otherwise) 
to generate/pass values "on demand".  So a different approach is in order.  The 
following code seems to work, although I wouldn't recommend it for production code:

--->8---
def integers(n):
     while 1:
         yield n
         n = n + 1

i = integers(0)

def format_with_generator(formatstr, gen):
     arguments = []
     while 1:
         try:
             s = formatstr % tuple(arguments)
         except TypeError, e:
             if e.args[0] == 'not enough arguments for format string':
                 item = gen.next()
                 arguments.append(item)
             else:
                 raise
         else:
             return s

fs = "Gimme a %s and a %s and a %s!"
print format_with_generator(fs, i)
print format_with_generator(fs, i)
--->8---

Hope this helps!

--
Hans Nowak (hans at zephyrfalcon.org)
http://zephyrfalcon.org/




More information about the Python-list mailing list