evalstr
Shannon --jj Behrens
jjinux at yahoo.com
Wed Jul 11 05:21:16 EDT 2001
Hello All,
I wrote a useful C module for doing string
interpolation. I find it indespensible when working
with large blocks of triple-quoted text. When working
with large blocks of triple-quoted text, nothing else
is quite as convenient. Here's the Python doc:
"""Evaluate a string with embedded python
expressions.
This is a Python version of the function evalstr,
which is used for
variable interpolation.
For instance,
a = 5
evalStr("I have $a$ dogs.")
will return
"I have 5 dogs."
The code between the $'s can be any valid Python
expression. I'll just
basically do
str(eval(expression), yourGlobals, yourLocals)
Since eval is being used, the expression must
return some value. To escape
$'s in s, just use $$ (even within expressions).
To use a different
character than $, pass the desired character in
the second (optional)
argument. If there are an odd number of $
symbols, a ValueError exception
will be raised. Here are some additional examples
(assuming a = 5):
"My dog is $a$ years old." -> "My dog is 5 years
old.",
"I have $$5.00" -> "I have $5.00",
"My $a$ year old dog has $$5.00" -> "My 5 year old
dog has $5.00",
"My dog has $'$$%s.' % a$" -> "My dog has $5.",
"My dog has $'$$' + str(a) + '.'" -> ValueError
exception,
"My dog is $a$.$" -> ValueError exception,
"$$ is a char." -> "$ is a char.",
"$a$ is a number." -> "5 is a number.",
"$a$" -> "5",
"$a" -> ValueError exception,
"I have a $$" -> "I have a $",
"" -> "",
"Spam" -> "Spam",
"$" -> ValueError exception,
"$ evalstr('I am #a#.', '#') $" -> "I am 5."
"""
Please forgive my arrogance, but I think that it might
even be useful enough to be included as a standard
module. If, not perhaps you guys might have some
suggestions as to what I can do with it. You may
download the entire packages from:
<http://ironorchid.com/jjinux/evalstr.tar.gz>
Cheers,
-jj
__________________________________________________
Do You Yahoo!?
Get personalized email addresses from Yahoo! Mail
http://personal.mail.yahoo.com/
More information about the Python-list
mailing list