String handling and the percent operator

Bruno Desthuilliers onurb at xiludom.gro
Fri Jul 14 04:21:05 EDT 2006


Tom Plunket wrote:
> I have some code to autogenerate some boilerplate code so that I don't
> need to do the tedious setup stuff when I want to create a new module.
> 
> So, my script prompts the user for the module name, then opens two
> files and those files each get the contents of one of these functions:
> 
> def GetPyContents(module):
> 	boilerplate = \
> """
> class %s:
> 	pass
> 	
> if __name__ == '__main__':
> 	import unittest
> 	unittest.main('%s_t')
> """
> 	
> 	return boilerplate % ((module,) * 2)
> 	
> def GetTestContents(module):
> 	boilerplate = \
> """from %s import *
> import unittest
> 
> class Test%s(unittest.TestCase):
> 	def testConstruction(self):
> 		self.failUnless(%s())
> 		
> 	def testWriteMoreTests(self):
> 		self.fail('This test should fail.')
> 		
> if __name__ == '__main__':
> 	unittest.main()
> """
> 
> 	return boilerplate % ((module,) * 3)
> 
> My question is, I don't like hardcoding the number of times that the
> module name should be repeated in the two return functions.  Is there
> an straight forward (inline-appropriate) way to count the number of
> '%s'es in the 'boilerplate' strings?  ...or maybe a different and more
> Pythonic way to do this?  (Maybe I could somehow use generators?)

Python's string formatting comes in two flavours : positional (the one
you used in your above example), and keywords:

tpls = [
  "%(name1)s is %(name1)s and %(name2)s is %(name2)s",
  "what about %(name2)s for %(name1)s ?",
  "Now we only deal with %(name1)s",
  ]

data = {'name1' : 'parrot', 'name2': 'dead'}

for tpl in tpls:
  print tpl % data

As you can see, the keyword flavour doesn't care about positions nor
repetitions.

You may also want to look at more featured templating solutions like
empy, cheetah, etc...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list