By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,262 Members | 1,161 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,262 IT Pros & Developers. It's quick & easy.

Yet another string interpolation function...

P: n/a
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

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
# expression interpolation
print interp('This is an #{test1 + " (and another " + test1 + ")"}
and an int (#{test2})')


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


Mar 4 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.