RE: replace %(word) in a string

Discussion in 'Python' started by Marc Boeren, Sep 17, 2003.

  1. Marc Boeren

    Marc Boeren Guest

    Hi,

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


    You mean
    base_string % dictionary

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

    "lovers"}
    'hello, python lovers !'

    Notice the trailing s in %(word)s!

    Cheerio, Marc.
     
    Marc Boeren, Sep 17, 2003
    #1
    1. Advertising

  2. Marc Boeren

    Mirko Zeibig Guest

    On Wed, 17 Sep 2003 at 08:45 GMT, Marc Boeren <> wrote:
    >
    > Hi,
    >
    >> For example with the string: "hello, %(word1) %(word2) !" and the
    >> dictionary: {"word1" : "python", "word2" : "lovers"} the final string
    >> would be: "hello python lovers"

    >
    > You mean
    > base_string % dictionary
    >
    >>>> "hello, %(word1)s %(word2)s !" % {"word1" : "python", "word2" :

    > "lovers"}
    > 'hello, python lovers !'
    >
    > Notice the trailing s in %(word)s!


    Especially useful together with the locals() function, which returns a
    dictionary of locally defined variables:

    def foo():
    a = "Hello"
    b = "World"
    print "%(a)s %(b)s" % locals()

    foo()

    Regards
    Mirko
     
    Mirko Zeibig, Sep 17, 2003
    #2
    1. Advertising

  3. Mirko Zeibig <> said :

    > Especially useful together with the locals() function, which returns a
    > dictionary of locally defined variables:
    >
    > def foo():
    > a = "Hello"
    > b = "World"
    > print "%(a)s %(b)s" % locals()


    Yes, that's a wonderful feature. Recently though, I've wondered a couple of
    times : is there an easy way to substitute with both local AND global
    variables ?...


    --
    YAFAP : http://www.multimania.com/fredp/
     
    Fred Pacquier, Sep 17, 2003
    #3
  4. Marc Boeren

    Peter Hansen Guest

    Fred Pacquier wrote:
    >
    > Mirko Zeibig <> said :
    >
    > > Especially useful together with the locals() function, which returns a
    > > dictionary of locally defined variables:
    > >
    > > def foo():
    > > a = "Hello"
    > > b = "World"
    > > print "%(a)s %(b)s" % locals()

    >
    > Yes, that's a wonderful feature. Recently though, I've wondered a couple of
    > times : is there an easy way to substitute with both local AND global
    > variables ?...


    tempDict = locals()
    tempDict.update(globals())

    then just use tempDict for the dictionary...

    You can also do it the other way around, of course, and you must decide
    which you really want since the last-added dictionary will of course
    mask any keys which are also in the first-added dictionary.

    -Peter
     
    Peter Hansen, Sep 17, 2003
    #4
  5. Fred> Yes, that's a wonderful feature. Recently though, I've wondered a
    Fred> couple of times : is there an easy way to substitute with both
    Fred> local AND global variables ?...

    Sure, search the list archives for something like EvalDict. Basically, you
    want a class which behaves like a dict, but will search through multiple
    dictionaries looking for matching keys.

    Skip
     
    Skip Montanaro, Sep 17, 2003
    #5
  6. Marc Boeren

    Peter Hansen Guest

    Peter Hansen wrote:
    >
    > Fred Pacquier wrote:
    > >
    > > Mirko Zeibig <> said :
    > >
    > > > Especially useful together with the locals() function, which returns a
    > > > dictionary of locally defined variables:
    > > >
    > > > def foo():
    > > > a = "Hello"
    > > > b = "World"
    > > > print "%(a)s %(b)s" % locals()

    > >
    > > Yes, that's a wonderful feature. Recently though, I've wondered a couple of
    > > times : is there an easy way to substitute with both local AND global
    > > variables ?...

    >
    > tempDict = locals()
    > tempDict.update(globals())


    Hmmm... should that be locals().copy() ? Probably...
     
    Peter Hansen, Sep 17, 2003
    #6
  7. Marc Boeren

    Max M Guest

    Fred Pacquier wrote:

    > Yes, that's a wonderful feature. Recently though, I've wondered a couple of
    > times : is there an easy way to substitute with both local AND global
    > variables ?...


    It can often be a good idea to create an adapter/pattern for string
    substitutions. Then the wrapper can "massage" the dict values before
    they go into the string.

    Here only a simple version is needed though (untested).

    class Wrapper:

    def __getitem__(self, key):
    return locals().get(key, globals[key])


    'Some string sub %(some_var)s' % Wrapper()


    regards max M
     
    Max M, Sep 17, 2003
    #7
  8. On 17 Sep 2003 16:30:08 GMT, Fred Pacquier wrote:

    > Mirko Zeibig <> said :
    >
    > > Especially useful together with the locals() function, which returns
    > > a dictionary of locally defined variables:
    > >
    > > def foo():
    > > a = "Hello"
    > > b = "World"
    > > print "%(a)s %(b)s" % locals()

    >
    > Yes, that's a wonderful feature. Recently though, I've wondered a
    > couple of times : is there an easy way to substitute with both local
    > AND global variables ?...
    >


    You can substitute local and global variables. But you can do much more.
    You can write a python expression in %(...)s if the object on the right
    side of % looks like a dictionnary and can evaluate its argument. For
    example I often this piece of code:

    class I:
    def __getitem__(self, item):
    frame = sys._getframe(1)
    return eval(item, frame.f_globals, frame.f_locals)

    As I only need one instance of I, I use:

    I = I()

    Then I can write thing like that:

    word1 = "python"
    word2 = "lovers"

    print "Hello, %(word1)s %(word2)s !"%I

    And even:

    print "1 + 1 = %(1+1)s"%I

    But you must keep in mind that the use of eval may not be safe.


    Christophe.




    --

    (o_ Christophe Delord __o
    //\ http://christophe.delord.free.fr/ _`\<,_
    V_/_ mailto: (_)/ (_)
     
    Christophe Delord, Sep 17, 2003
    #8
  9. On Wed, 17 Sep 2003 21:01:57 +0200
    Max M <> wrote regarding Re: replace %(word) in a string:

    > class Wrapper:
    >
    > def __getitem__(self, key):
    > return locals().get(key, globals[key])


    Shouldn't that be:
    return locals().get(key, globals()[key])
    ^^

    Cheers,
    Bill
     
    William Trenker, Sep 17, 2003
    #9
  10. Marc Boeren

    Peter Otten Guest

    Max M wrote:

    > Fred Pacquier wrote:
    >
    >> Yes, that's a wonderful feature. Recently though, I've wondered a couple
    >> of times : is there an easy way to substitute with both local AND global
    >> variables ?...

    >
    > It can often be a good idea to create an adapter/pattern for string
    > substitutions. Then the wrapper can "massage" the dict values before
    > they go into the string.
    >
    > Here only a simple version is needed though (untested).
    >
    > class Wrapper:
    >
    > def __getitem__(self, key):
    > return locals().get(key, globals[key])
    >
    >
    > 'Some string sub %(some_var)s' % Wrapper()


    I fear that the locals() you access with your wrapper class are the local
    variables of the Wrapper.__getitem__() method. Also globals()[key] is
    evaluated on *every* call of __getitem__() and thus fails if you try to
    access a local variable that does not shade a global variable.
    Assuming class Wrapper and client code are both in the same module, your
    code is pretty much equivalent to

    'Some string sub %(some_var)s' % globals()

    Peter
     
    Peter Otten, Sep 18, 2003
    #10
  11. Fred Pacquier <> said :

    > Yes, that's a wonderful feature. Recently though, I've wondered a
    > couple of times : is there an easy way to substitute with both local
    > AND global variables ?...


    Thanks to all who responded to that one... I half-feared that I'd asked a
    really silly question, but it turns out it's not quite so trivial in the
    general case after all, and there's been quite some discussions about it
    before. In any case I learned a few things from your input as usual, so it
    was a useful question ;-)

    In my very simple case I'm only missing *one* var from locals(), so the
    ugly one-line hack of reassigning lvar = gvar inside the function seems
    quite enough after all...

    --
    YAFAP : http://www.multimania.com/fredp/
     
    Fred Pacquier, Sep 18, 2003
    #11
    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. Maxime Biais

    replace %(word) in a string

    Maxime Biais, Sep 17, 2003, in forum: Python
    Replies:
    1
    Views:
    324
    Max M
    Sep 17, 2003
  2. Replies:
    20
    Views:
    918
    Steven D'Aprano
    Oct 23, 2005
  3. Alun
    Replies:
    3
    Views:
    4,574
    Masudur
    Feb 18, 2008
  4. Prasad S
    Replies:
    2
    Views:
    245
    Dr John Stockton
    Aug 27, 2004
  5. V S Rawat
    Replies:
    5
    Views:
    319
    Richard Cornford
    Jul 3, 2007
Loading...

Share This Page