embed data inside string

Fernando Pérez fperez528 at yahoo.com
Thu May 16 12:45:31 EDT 2002


Julia Bell wrote:

> I recognize that the formatted strings are just as simple as the example
> line I gave
> using the concatenation.   (I just used the simple example to demonstrate
> the point). My actual application is more complex (lots of escaped
> characters, combination of single and double quotes, etc. - just a messy
> string to be creating - so I was hoping to at least eliminate the parts of
> the definition that involved leaving the quoted portion to evaluate the
> parameter).
> 
> But, from the responses it looks like the concatenation I'm using is
> probably the easiest way to go.
> 

A couple of points:

- first, welcome to the never ending argument about string interpolation (or 
lack thereof) in python. I'm one of those people who thinks that it's a truly 
useful feature to have, but I've stopped arguing for it. Look at pep215 for 
details: http://www.python.org/peps/pep-0215.html

If you really want to use this, I recommend grabbing Ping's reference 
implementation of pep215, the Itpl module. For complex problems it beats the 
hell out of the %(name)s games.

- second, string concatenation has a potential memory problem: because python 
strings are immutable, every '+' operation requires the creation of a new 
string. Just try doing the following at the interactive prompt:

In [2]: s='*'*10000000

which has no problems, versus:


In [3]: s=''

In [4]: for i in xrange(1000000):
   ...:   s += '*'*10
   ...:

and you'll see your cpu usage peg at 100% for quite a while. Still, the final 
result is the same.

This may not matter in your case, but you must be aware of it. If it does, for 
complex operations the 'python' way is to use:

'var1= %(var1)s blah.... var2 is: %(var2)s ...' % {'var1':var1,'var2':var2}

Or just use Itpl and have a clean:

itpl('var1 = $var1 blah... var2 is $var2').

As I said, I stopped trying to push these ideas because most people seem happy 
playing silly %()s games with manually constructed dictionaries or passing 
locals() to the rhs of %. Oh well...

Cheers,

f.



More information about the Python-list mailing list