replace %(word) in a string

Mirko Zeibig mirko-lists at zeibig.net
Wed Sep 17 07:40:29 EDT 2003


On Wed, 17 Sep 2003 at 08:45 GMT, Marc Boeren <M.Boeren at guidance.nl> wrote:
> 
> Hi,
> 
>> For example with the string: "hello, %(word1) %(word2) !" and the
>> dictionary: {"word1" : "python", "word2" : "lovers"} the final string
>> would be: "hello python lovers"
> 
> You mean 
> 	base_string % dictionary
> 
>>>> "hello, %(word1)s %(word2)s !" % {"word1" : "python", "word2" :
> "lovers"}
> 'hello, python lovers !'
> 
> Notice the trailing s in %(word)s!

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()

foo()

Regards
Mirko




More information about the Python-list mailing list