String formatting with the format string syntax

Andre Alexander Bell post at andre-bell.de
Wed Sep 15 06:35:23 EDT 2010


On 09/15/2010 10:48 AM, Peter Otten wrote:
> I personally would not be too concerned about the leading underscore, but
> you can use
>
> string.Formatter().parse(template)
>
> instead.

Thanks for this pointer. I like it this way. So if I now combine your 
generator with your suggestion, I end up with something like this:

def extract_names(t, recurse=1):
     import string
     for _, name, fmt, _ in string.Formatter().parse(t):
         if name is not None:
             yield name
         if recurse and fmt is not None:
             for name in extract_names(fmt, recurse-1):
                 yield name

Pretty cool. Thanks a lot.

Andre



More information about the Python-list mailing list