ignoring some placeholders in string formatting

Tim Chase python.list at tim.thechases.com
Thu Feb 11 02:53:44 CET 2010


Michal Ludvig wrote:
> URL="http://xyz/blah?session=%(session)s&message=%(message)s"
> 
> is it possible to fill in only 'session' and leave "%(message)s" as is
> when it isn't present in the values dict?
> 
> For example:
> URL % { 'session' : 123 }
> raises KeyError because of missing 'message' in the dict.
> 
> I could indeed replace '%(session)s' with a string replace or regexp but
> that's not very elegant ;-)

You can use a defaultdict instead of a regular dict:

   from collections import defaultdict
   d = defaultdict(str)
   d['session'] = 123
   URL="http://xyz/blah?session=%(session)s&message=%(message)s"
   print URL % d

-tkc






More information about the Python-list mailing list