468,510 Members | 1,753 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,510 developers. It's quick & easy.

replace %(word) in a string

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
Jul 18 '05 #1
1 2812
Maxime Biais wrote:
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"}
'hello, python lovers !'


regards Max M

Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by - ions | last post: by
1 post views Thread by adam lital | last post: by
reply views Thread by Balakrsihna | last post: by
3 posts views Thread by Craig | last post: by
1 post views Thread by Michael Yanowitz | last post: by
12 posts views Thread by implement | last post: by
3 posts views Thread by Hvid Hat | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.