Yet another string interpolation function...

M

MonkeeSage

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top