String formatting with the format string syntax

Andre Alexander Bell post at andre-bell.de
Tue Sep 14 12:59:48 EDT 2010


Hello,

I'm used to write in Python something like

 >>> s = 'some text that says: %(hello)s'

and then have a dictionary like

 >>> english = { 'hello': 'hello' }

and get the formatted output like this:

 >>> s % english

Occasionally I want to extract the field names from the template string. 
I was used to write a class like

class Extractor(object):
     def __init__(self):
         self.keys = []
     def __getitem__(self, key):
         self.keys.append(key)
         return ''

and use it like this:

 >>> e = Extractor()
 >>> res = s % e
 >>> e.keys
['hello']

Now Python has the format method for string formatting with the more 
advanced handling. So I could as well write

 >>> s = 'some text that says: {hello!s}'
 >>> s.format(hello='hello')

My question is, if I do have a string template which uses the newer 
format string syntax, how do I best extract the field information?

I found the str._formatter_parser() method which I could use like this:

keys = []
for (a, key, c, d) in s._formatter_parser():
     if key:
         keys.append(key)

Is there a more elegant solution?
What are a, c, d?
Where can I find additional information on this method?
Should one use a method that actually starts with an _?
Couldn't this one change any time soon?

Thanks for any help


Andre



More information about the Python-list mailing list