Yet another string interpolation function...



There are several string interpolation functions, as well as
string.Template. But here's yet another. This one emulates ruby's
inline interpolation syntax (using #{}), which interpolates strings as
well as expressions. NB. It uses eval(), so only use it in trusted
contexts!

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()

Recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502257

Ok, now tell me all the things wrong with it! ;)

Regards,
Jordan

.



Relevant Pages

  • Re: Metacharacter problem in regexp
    ... wrong with regular expressions in Perl 5 and how are they going to look ... interpolation you've asked about and the klunky workaround I've sent ... any piece of program is a string. ... string as a regular expression. ...
    (perl.beginners)
  • Re: Expression Interpolation from input "template string"?
    ... Peter Fitzgibbons wrote: ... >>> What I don't know is how to get the interpolation to ... it's assuming that the stored string doesn't contain any}'s in it. ... probably some other templating code out there, ...
    (comp.lang.ruby)
  • Re: Optimization in PERL
    ... use single quotes rather than doubles. ... Print 'I am a static string I don't want to get interpolated'; ... is no interpolation going on, and you certainly won't measure any ... the compile time for large strings (but as you point out, ...
    (perl.beginners)
  • Re: what i am doing wrong here .. getting LDAP_STRONG_AUTH_NOT_SUPPORTED
    ... > string you evidently want interpolated. ... Interpolation does not occur in ... > of your lConnect routine to see if it failed or not. ... (NOTE without SASL) ...
    (comp.lang.perl.misc)
  • Re: double quotes vs. single quotes (was Re: hash as argument)
    ... :) Tom Christiansen say that they always use double quotes... ... :) Double quotes without interpolation or backslash escapes tricks ... :) that string than is necessary. ... nor do I think 'single quoted string'. ...
    (comp.lang.perl.misc)