String handling and the percent operator
Simon Forman
rogue_pedro at yahoo.com
Thu Jul 13 19:12:31 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?)
>
> thx.
> -tom!
strings have a count() method.
Since you know that you won't have things like '%%s' in your
boilerplate, it's perfectly reasonable to use:
return boilerplate % ((module,) * boilerplate.count('%s'))
in your code.
Peace,
~Simon
return boilerplate % ((module,) * 3)
More information about the Python-list
mailing list