Brad Cox wrote:
> PS: The token (+ vs , vs nothing) isn't important. What *is* is that
> the result winds up as a string, not array, tuple, etc.
The string formatting always yields a string.
> PPS: Probably harder, supporting expansion of variables within strings
> ala' perl would immediately make python a favorite. The ${variable}s
> workaround that was offered here earlier is a bit obscure for heavily
> used stuff like expanding variable information into html template files.
I'm not sure how string formatting is "obscure" - it is described
in the python tutorial:
http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000
and it is heavily used in Python code (cd jython/Lib; grep \% *py if you'd like
a lot of examples...).
Also, it is likely to be faster than '+' would be...
BTW, watch your characters: percent and parens, not dollar and braces
> Ideally, this should work for any expression (variables, subroutine
> calls, arrays, tuples, etc).
Ahh, you want a formatter that evaluates expressions?
Not hard to make one.
Since named-value % formatting is based on dictionaries, you can replace the dictionary
with your own class with a "__getitem__" function. This lets you completely replace
the % evaluation with whatever you'd like:
--- formatter.py ---
import operator
class Formatter:
def __init__( self, locals=None ):
self.locals = locals or globals()
def __getitem__( self, name ):
return eval( name, self.locals )
asdf=10
template = """asdf=%(asdf)s
simple expression=%(20+30)s
complex expression=%(reduce(operator.add, range( 10 )))s
hairier than you want: %(Template( {"one":1, "two":4, "four":16, "4":16} ).format( "Square of four is %(four)s, but the digit 4 is %(4)s" ))s
"""
print template % Formatter()
----
output is:
>>> ## working on region in file d:/TEMP/python-3181zD...
asdf=10
simple expression=50
complex expression=45
hairier than you want: Square of four is 16, but the digit 4 is 4
>>>
Gosh, but I love Python. :-)
Bonus points if you figure out why the outputs of four & 4 are different. :-)
kb
|