replace %(word) in a string

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


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:


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

Maxime Biais

More information about the Python-list mailing list