I've been trying to learn new things from the Cookbook, but here's a recipe the utility of which I don't understand at all. Why interpolation (whether the ruby way or not)? Maybe a better example than the couple given would help me? 

The description is

"Interpolate variables and expressions in strings the ruby way. This is similar in functionality to recipe 496885, though implemented differently and with a different interpolation syntax."


import sys, re
def interp(string):
  locals  = sys._getframe(1).f_locals
  globals = sys._getframe(1).f_globals
  for item in re.findall(r'#\{([^{]*)\}', string):
    string = string.replace('#{%s}' % item,
                           
str(eval(item, globals, locals)))
  return string

test1 = 'example'
def tryit():
  test2 = 1
  # variable interpolation
  print interp('This is an #{test1} (and another #{test1}) and an
int (#{test2})')
  # _expression_ interpolation
  print interp('This is an #{test1 + " (and another " +
test1 + ")"} and an int (#{test2})')
tryit()

This is at < http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502257 >

Thanks,

Dick Moores
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to