Yet another string interpolation function...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • MonkeeSage

    #1

    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:



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

    Regards,
    Jordan

Working...