» String interpolation in python +
In python, the standard way to do string interpolation is to use the % operator. There are some bells and wistles to it, like named substitutions, but overall it behaves much the same as the C printf function on which it was modeled. On the other hand, in ruby you can use inline interpolation with #{} inside a string, which combines perl's ${} and $() into one. I personally prefer the latter method. As of 2.4, python has a similar interpolation method, using the string.Template module, however it is still not as terse (and imo, clean). So here is a simple function to emulate the ruby way (with both expression and variable interpolation).
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})')
# standard way
print 'This is a %s and a %s and an int (%d)' % (test1, test1, test2)
# since 2.4
from string import Template
map = sys._getframe(0).f_globals
map.update(sys._getframe(0).f_locals)
print 'This is a %(test1)s and a %(test1)s and an int (%(test2)d)' % map
print Template('This is a $test1 and a $test1 and an int ($test2)').substitute(map)
tryit()
I don't mind using the printf style of interpolation, but I prefer the inline method better personally.
[Edit:] Added a cookbook recipe for this.
1 Comments:
Great work.
November 10, 2008 at 3:02 PM
Post a Comment
<< Home