how to get all the "variables" of a string formating?

Calvin Spealman ironfroggy at gmail.com
Wed Dec 6 12:52:42 EST 2006


On 6 Dec 2006 09:41:36 -0800, GHUM <haraldarminmassa at gmail.com> wrote:
> imagine:
>
>
> template=""" Hello %(name)s, how are you %(action)s"""
>
>
> we can use it to do things like:
>
> print template % dict (name="Guido", action="indenting")
>
>
> Is there an easy (i.e.: no regex) way to do get the names of all
> parameters?
>
> get_parameters(template) should return ["name", "action"]
>
>
> Python has to do this somewhere internally..... how to access this
> knowledge?
>
> Harald
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I am not aware of anything in the stdlib to do this easily, but its
pretty easy to get them. See this example:

class format_collector(object):
   def __init__(self):
      self.names = []
   def __getitem__(self, name):
      self.names.append(name)
      return ''

collector = format_collector()
"%(foo)s %(bar)s" % collector
assert collector.names == ['foo', 'bar']

Of course, wrapping this functionality into a simple function is
straightforward and will look better.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/



More information about the Python-list mailing list