ignoring some placeholders in string formatting
MRAB
python at mrabarnett.plus.com
Wed Feb 10 21:51:06 EST 2010
Michal Ludvig wrote:
> Hi all,
>
> when I've got a string, say:
>
> 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 ;-)
>
> Is there any way to tell the formatter to use only what's available and
> ignore the rest?
>
You could write a class inheriting from dict which, for example, returns
"%(key)s" if the key "key" is absent:
>>> class IgnoreDict(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return "%%(%s)s" % key
>>> d = {'session': 123}
>>> URL = "http://xyz/blah?session=%(session)s&message=%(message)s"
>>> URL % d
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
URL % d
KeyError: 'message'
>>> URL % IgnoreDict(d)
'http://xyz/blah?session=123&message=%(message)s'
More information about the Python-list
mailing list