String format - resolve placeholders names

Denis McMahon denismfmcmahon at gmail.com
Fri Nov 20 12:08:21 EST 2015


On Fri, 20 Nov 2015 16:53:47 +0100, Peter Otten wrote:

> Ervin Hegedüs wrote:

>> Python has a good string formatter, eg. I can do this:

>> s = "{who} likes {what}"
>> d = {'who': "Adam", 'what': "ants"}
>> s.format(**d)

>> result:
>> 'Adam likes ants'

>> Is it possible, and if yes, how to resolve the placeholders names in
>> string?

>>>> import string for item in string.Formatter().parse("{who} likes
>>>> {what}"):
> ...     print(item)
> ...
> ('', 'who', '', None)
> (' likes ', 'what', '', None)

Or even:

>>> s = "{who} likes {what}"
>>> d = {'who': "Adam", 'what': "ants"}
>>> keys = [x[1] for x in string.Formatter().parse(s)]
>>> keys
['who', 'what']

then ...

for key in keys:
    if key not in d:
        raise KeyError("Missing key '{}' in format string '{}'".format
(key, s))

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list