replace %(word) in a string

Discussion in 'Python' started by Maxime Biais, Sep 17, 2003.

  1. Maxime Biais

    Maxime Biais Guest

    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)


    --
    Maxime Biais
     
    Maxime Biais, Sep 17, 2003
    #1
    1. Advertising

  2. Maxime Biais

    Max M Guest

    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
     
    Max M, Sep 17, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Marc Boeren

    RE: replace %(word) in a string

    Marc Boeren, Sep 17, 2003, in forum: Python
    Replies:
    10
    Views:
    613
    Fred Pacquier
    Sep 18, 2003
  2. Replies:
    20
    Views:
    928
    Steven D'Aprano
    Oct 23, 2005
  3. Alun
    Replies:
    3
    Views:
    4,650
    Masudur
    Feb 18, 2008
  4. Prasad S
    Replies:
    2
    Views:
    258
    Dr John Stockton
    Aug 27, 2004
  5. V S Rawat
    Replies:
    5
    Views:
    345
    Richard Cornford
    Jul 3, 2007
Loading...

Share This Page