Thursday, October 23, 2008

Quick way to interpolate local variables into a string

x = "variable 1"
y = "variable 2"

"%(x)s %(y)s" % locals()

This is so easy it hurts.

We can use the dict syntax to interpolate variables into a string, which is often more convenient; and, we can use locals() to return a dict of all locally-bound variables.

No comments: