String formatting with the format string syntax
Thomas Jollans
thomas at jollybox.de
Tue Sep 14 15:20:25 EDT 2010
On Tuesday 14 September 2010, it occurred to Miki to exclaim:
> You can use ** syntax:
> >>> english = {'hello':'hello'}
> >>> s.format(**english)
No, you can't. This only works with dicts, not with arbitrary mappings, or
dict subclasses that try to do some kind of funny stuff.
>
> On Sep 14, 9:59 am, Andre Alexander Bell <p... at andre-bell.de> wrote:
> > 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