On Mar 31, 3:29 am, Terry Reedy <tjre...@udel.edu> wrote: > On 3/31/2012 2:22 AM, Yingjie Lan wrote: > > > Hi all, > > > I'd really like to share this idea of string interpolation for formatting. > > Let's start with some code: > > > >>> name = "Shrek" > > >>> print( "Hi, $name$!") > > Hi, Shrek! > > >>> balls = 30 > > >>> print( "We have $balls$ balls.") > > We have 30 balls > > You can already do essentially that without adding a special-case string > formatting method to the general methods we already have. > > >>> balls = 5 > >>> people = 3 > >>> 'The {people} people have {balls} balls.'.format(**locals()) > 'The 3 people have 5 balls.' >
I was wondering how much of a performance penalty you pay for using the **locals() idiom, because I use it myself sometimes. It turns out there is a slight penalty for "**locals()" vs. explicitly passing in arguments to format (e.g. ".format(balls=balls, people=people"), although it's probably negligible in 99.9% of use cases. def yo(a): x = 1 y = 2 z = 3 a = b = c = d = 7 for i in range(10): # s = "{x} {y} {z}".format(**locals()) s = "{x} {y} {z}".format(x=x, y=y, z=z) for i in range(10000): yo(i) # .150s for **locals() # .131s for explicit x/y/z -- http://mail.python.org/mailman/listinfo/python-list