Variables in strings..

David Bolen db3l at fitlinxx.com
Mon Jul 24 20:41:19 EDT 2000


Gabriel Ambuehl <gabriel_ambuehl at buz.ch> writes:

> Hello Steve,
> Monday, July 24, 2000, 12:52:30 PM, you wrote:
> 
> >   print "Hello %s" % names[1]
> > to the eyes of anyone but a Perl afficionado.
> 
> Perhaps. But in real world (tm) CGI scripts, one needs more than just
> one variable in there. I've got Perl scripts who insert aroun 40
> variables (including array slices) during one print <<"EOF"
> instruction. I could live with the "%(myvar)" % vars() syntax if there
> would be a possibility to reference to lists and dictionary entries as
> well. Without it, it's a real pain to quickly write CGI scripts.

It sounds like what you just want is a module that can interpret
variables within strings more like you're used to with Perl :-)

By pure chance I happened across one recently at
http://www.lfw.org/python/Itpl15.py.  From the module's docstring:

  This module lets you quickly and conveniently interpolate values into
  strings (in the flavour of Perl or Tcl, but with less extraneous
  punctuation).  You get a bit more power than in the other languages,
  because this module allows subscripting, slicing, function calls,
  attribute lookup, or arbitrary expressions.  Variables and expressions
  are evaluated in the namespace of the caller.

  The itpl() function returns the result of interpolating a string, and
  printpl() prints out an interpolated string.  Here are some examples:

      from Itpl import printpl
      printpl("Here is a $string.")
      printpl("Here is a $module.member.")
      printpl("Here is an $object.member.")
      printpl("Here is a $functioncall(with, arguments).")
      printpl("Here is an ${arbitrary + expression}.")
      printpl("Here is an $array[3] member.")
      printpl("Here is a $dictionary['member'].")

  (...)


--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list