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 - [email protected] http://mail.python.org/mailman/listinfo/tutor
