Get dictionary-keys used to format a string

Bernhard Herzog herzog at online.de
Thu Mar 2 13:52:43 EST 2000


"Fredrik Lundh" <effbot at telia.com> writes:

> Michael Ströder <michael.stroeder at inka.de> wrote:
> > Hence the example from the Python docs:
> >
> > '%(language)s has %(count)03d quote types.' % vars()
> >
> > I would like to extract the keys in the formatting string to a list.
> > Well I can parse it myself but is there a built-in function to
> > extract a list/tuple of the dictionary keys, e.g.
> > ['language','count'] in this case?
> 
> 
> >>> s = '%(language)s has %(count)03d quote types.'
> 
> >>> import re
> >>> re.findall(r'%\((\w+)\)', s)
> ['language', 'count']
> 
> hope this helps!

Hmm, it doesn't deal with %% correctly:

>>> s = "%%(regexps)s %(are)s %%%(tricky)d"
>>> re.findall(r'%\((\w+)\)', s)
['regexps', 'are', 'tricky']
>>> 

This is better:

>>> re.findall(r'(?:[^%]|^)(?:%%)*%\((\w+)\)', s)
['are', 'tricky']

I'm not sure whether it really covers all special cases, though, or
whether there's a simpler regexp.

-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list