replace %(word) in a string

Christophe Delord christophe.delord at free.fr
Wed Sep 17 16:14:50 EDT 2003


On 17 Sep 2003 16:30:08 GMT, Fred Pacquier wrote:

> Mirko Zeibig <mirko-lists at zeibig.net> said :
> 
> > Especially useful together with the locals() function, which returns
> > a dictionary of locally defined variables:
> > 
> > def foo():
> >     a = "Hello"
> >     b = "World"
> >     print "%(a)s %(b)s" % locals()
> 
> Yes, that's a wonderful feature. Recently though, I've wondered a
> couple of times : is there an easy way to substitute with both local
> AND global variables ?...
> 

You can substitute local and global variables. But you can do much more.
You can write a python expression in %(...)s if the object on the right
side of % looks like a dictionnary and can evaluate its argument. For
example I often this piece of code:

class I:
    def __getitem__(self, item):
        frame = sys._getframe(1)
        return eval(item, frame.f_globals, frame.f_locals)

As I only need one instance of I, I use:

I = I()

Then I can write thing like that:

word1 = "python"
word2 = "lovers"

print "Hello, %(word1)s %(word2)s !"%I

And even:

print "1 + 1 = %(1+1)s"%I

But you must keep in mind that the use of eval may not be safe.


Christophe.




-- 

(o_   Christophe Delord                     __o
//\   http://christophe.delord.free.fr/   _`\<,_
V_/_  mailto:christophe.delord at free.fr   (_)/ (_)




More information about the Python-list mailing list