Partial substitution similar to str % dict

Chris Liechti cliechti at gmx.net
Sun Aug 18 13:40:35 EDT 2002


Stefan Schwarzer <sschwarzer at sschwarzer.net> wrote in
news:3D5FCB9B.1060108 at sschwarzer.net: 
> I would like to do "partial" string substitutions, for example
> 
> >>> partial_substitute( "%(foo)s-%(bar)s", {'foo': 'abc'} )
> 'abc-%(bar)s'

hackish:  ;-) 

>>> class Subst(dict):
... 	def __getitem__(self, item):
... 		if item in self:
... 			return dict.__getitem__(self, item)
... 		else:
... 			return "%%(%s)s" % item
... 			
>>> "%(foo)s-%(bar)s" % Subst({'foo': 'abc'})
'abc-%(bar)s'

cheers
chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list