Partial substitution similar to str % dict

Stefan Schwarzer sschwarzer at sschwarzer.net
Sun Aug 18 12:30:19 EDT 2002


Hello

I would like to do "partial" string substitutions, for example

 >>> partial_substitute( "%(foo)s-%(bar)s", {'foo': 'abc'} )
'abc-%(bar)s'

In contrast, if I use the normal string substitution operator I get

 >>> "%(foo)s-%(bar)s" % {'foo': 'abc'}
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
KeyError: bar

Is there an easy way to accomplish partial substitutions like in the first example?
How can the function partial_substitute be implemented?

Many thanks for your answers!

Stefan




More information about the Python-list mailing list