String formatting with %s

Tim Chase python.list at tim.thechases.com
Mon Dec 3 07:23:10 EST 2007


>> dictionary-key/value syntax), you can do something like:
>>>>> number = lambda x: dict((str(i+1), v) for (i,v) in enumerate(x))
>>>>> "%(2)s and %(1)s" % number(["A", "B"])
>
> Whoa - that'll take me a little while to figure out, but it looks intriguing! 

It basically just returns a dictionary that maps your
positional-index of your input to your input. Because keyword
substitution looks up a string in your dict, you have to convert
the index to a string.  And since you were using one-based
indexing rather than zero-based indexing, I added one to the
index before converting it to a string.  To help understand it,
watch each of the pieces in that function:

  >>> for z in enumerate(x):  print z
  >>> for z in ((i+1, v) for v in enumerate(x)):  print z
  >>> for z in ((str(i+1), v) for v in enumerate(x)):  print z
  >>> print number(["h","e","l", "l", "o"])

so you can see what's getting passed to the string-formatter.

If you're passing in a fixed parameter list (one that you
generate right there in the code, rather than some list you've
previously built up and would use with something like
"number(some_list)"), you can insert an asterisk between the
"lambda x"

>>> number = lambda *x: dict((str(i+1), v) for (i,v) in enumerate(x))

so it can be called a little more cleanly without the extra
"list'ification" like

>>> "%(2)s and %(1)s" % number("A", "B")

It just depends on what your common case is.

-tkc







More information about the Python-list mailing list