replace %(word) in a string

M

Maxime Biais

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 + re_res.group(3)
 
M

Max M

Maxime said:
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"


You are almost there.

"hello, %(word1)s %(word2)s !" % {"word1":"python", "word2":"lovers"}

regards Max M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top