"%(a)s ... %(b)s" % {'a': foo, 'b': '%(b)s'}

Michael Hudson mwh21 at cam.ac.uk
Sat Dec 4 10:26:54 EST 1999


Gerrit Holl <gerrit.holl at pobox.com> writes:

> Hello,
> 
> I'm facing the following problem. I set __version__ and now I set a string
> like this:
> 
> MAIL = '''From: someone <%(email)s>
> Subject: test
> 
> this is feedback.py %(version)
> ''' % {'version': __version__}
> 
> This raises a KeyError. I have to type:
> ... % {'version': __version__, 'email': '%(email)s'}
> 
> This is ugly! Isn't there a better way to fill in just SOME of the %(...)s
> values in a string and leave the rest as is?

If you know the order you will be filling the fields in, then you can
double up the `%' signs, like:

>>> __version__ = 1
>>> t = "%(version)s %%(email)s"%{"version":__version__}
>>> t
'1 %(email)s'

or you could do

>>> class NotQuiteDict:
	def __getitem__(self,item):
		if item == "version":
			return "1"
		else:
			return "%%(%s)s"%item

		
>>> c = NotQuiteDict()
>>> "%(version)s %(email)s"%c
'1 %(email)s'

which obviously needs generalisation, but I hope you get the idea.

Cheers,
Michael




More information about the Python-list mailing list