replace %(word) in a string

Max M maxm at
Wed Sep 17 21:01:57 CEST 2003

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

More information about the Python-list mailing list