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

Tim Chase python.list at tim.thechases.com
Wed Dec 6 14:03:47 EST 2006


>> Is there an easy (i.e.: no regex) way to do get the names of all
>> parameters?
>>
>> get_parameters(template) should return ["name", "action"]
>
> How about:
> 
> class gpHelper:
>     def __init__(self):
>         self.names = set()
>     def __getitem__(self, name):
>         self.names.add(name)
>         return 0
> 	
> def get_parameters(template):
>     hlp = gpHelper()
>     template % hlp
>     return hlp.names
> 
>>>> template=""" Hello %(name)s, how are you %(action)s"""
>>>> get_parameters(template)
> set(['action', 'name'])

(darn, if I didn't have nearly identical code/reply, but two 
posts beat me to the Send button)

Duncan's solution is a slightly more robust solution (returning 0 
rather than returning the empty string), as format strings allow 
for things like

"%(food)s costs $%(x)05.2f" % {
	'x':3.14159,
	'food':'a slice of pie'
	}

which will choke if it gets a string instead of a number for 
attempts to get "x".

It sure beats trying to hammer out a regexp or some stab at 
pyparsing it.  Though I suppose one could do something like

r = re.compile(r'%\(([^)]*)\)')

as most of the edge-cases that I can think of that would cause 
problems in a general case would be problems for the string 
formatting as well (balanced parens, etc)

-tkc








More information about the Python-list mailing list