replace %(word) in a string

Maxime Biais max at fr.fm
Wed Sep 17 10:32:02 CEST 2003


Hello,

I heard that is possible to replace %(word) in a string with a dictionary
containing { "word" : "replaced word" } with a function or a builtin from
the python library.

For example with the string: "hello, %(word1) %(word2) !" and the
dictionary: {"word1" : "python", "word2" : "lovers"} the final string
would be: "hello python lovers"

For the moment i use this code but i want something more pythonic:

str: 
var_dic: 

for i in var_dic:
        myre = re.compile("(.*)(\%\(%s\))(.*)" % i, re.IGNORECASE)
        re_res = myre.match(str)
        if re_res:
            str = re_res.group(1) + var_dic[i] + re_res.group(3)


-- 
Maxime Biais




More information about the Python-list mailing list