Iterate a format string over a list

Wayne Werner picture Wayne Werner · Jul 1, 2010 · Viewed 22.1k times · Source

In Lisp, you can have something like this:

(setf my-stuff '(1 2 "Foo" 34 42 "Ni" 12 14 "Blue"))
(format t "~{~d ~r ~s~%~}" my-stuff)

What would be the most Pythonic way to iterate over that same list? The first thing that comes to mind is:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in xrange(0, len(mystuff)-1, 3):
    print "%d %d %s" % tuple(mystuff[x:x+3])

But that just feels awkward to me. I'm sure there's a better way?


Well, unless someone later provides a better example, I think gnibbler's solution is the nicest\closest, though it may not be quite as apparent at first how it does what it does:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "{0} {1} {2}".format(*x)

Answer

John La Rooy picture John La Rooy · Jul 1, 2010
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "%d %d %s"%x

Or using .format

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "{0} {1} {2}".format(*x)

If the format string is not hardcoded, you can parse it to work out how many terms per line

from string import Formatter
num_terms = sum(1 for x in Formatter().parse("{0} {1} {2}"))

Putting it all together gives

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
fmt = "{0} {1} {2}"
num_terms = sum(1 for x in Formatter().parse(fmt))
for x in zip(*[iter(mystuff)]*num_terms):
    print fmt.format(*x)