Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl():
>>> from string import Template
>>> s, n, r = '0', 12, 3.4
>>> x = Template("$s $n $r")
>>> x.substitute(locals())
'0 12 3.4'If you want to bundle this up in a pp() function you have to do some magic to get the locals() of the caller. This seems to work:
>>> import sys
>>> def pp(s):
... loc = sys._getframe(1).f_locals
... print Template(s).substitute(loc)
...
>>> pp("$s $n $r")
0 12 3.4Kent
Bill Mill wrote:
Jeff,
I get the impression that many pythonistas don't like string interpolation. I've never seen a clear definition of why. Anyway, it's easy enough to add with the Itpl [1] module:
import Itpl, sys sys.stdout = Itpl.filter() s, n, r = 0, 0, 0 print "$s $n $r"
0 0 0
x = Itpl.itpl("$s $n $r") x
'0 0 0'
And, of course, you can give Itpl.itpl a nicer name; I usually call it pp(). If you don't need to change the behavior of the "print" statement, then you don't need the Itpl.filter() line.
[1] http://lfw.org/python/Itpl.py
Peace Bill Mill bill.mill at gmail.com
On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote:
To all those who talked about hating the symbology in Perl and the suggestion that it should be removed from a later version. I just remembered what you get for that symbology that I really do like about Perl: variable interpolation in strings:
C: sprintf(newstr,"%s %d %f",s,n,r);
Becomes a little nicer in Python with: newstr = '%s %d %f' % (s,n,r)
Although it's worse with: newstr = s + ' ' + str(n) + ' ' + str(r)
But in my mind nothing beats the Perl statement: newstr = "$s $n $r";
for clarity, ease of use, and maintainability.
Jeff
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
