Monday, June 8, 2009

TypeError: not enough arguments for format string

Got this error in some python code the other day:

TypeError: not enough arguments for format string


Essentially it means you have something like the following in your code:

"%s,%s,%s" % ('foo','bar')


Essentially it's saying there aren't enough strings to fill the placeholders. But it also means that there might be an errant % in the template string that you weren't anticipating such as:

"%s has 42% of the shares." % ('Bob')


which is annoying. A regex you can run on your code to roughly handle this is:

regex1 = re.compile('%(?![\(])')
regex2 = re.compile('%%+')
cooked_html = regex1.sub('%%', regex2.sub('%', raw_html))
I say roughly since if you're starting to run into these kinds of situations, you really need to start using a templating engine like jinja or mako. I'll switch to mako in the future.

No comments:

Post a Comment