Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99170

Re: String format - resolve placeholders names

From Denis McMahon <denismfmcmahon@gmail.com>
Newsgroups comp.lang.python
Subject Re: String format - resolve placeholders names
Date 2015-11-20 17:08 +0000
Organization A noiseless patient Spider
Message-ID <n2nk25$mns$1@dont-email.me> (permalink)
References <20151120145227.GB13994@arxnet.hu> <mailman.3.1448034840.2291.python-list@python.org>

Show all headers | View raw


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@gmail.com

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: String format - resolve placeholders names Peter Otten <__peter__@web.de> - 2015-11-20 16:53 +0100
  Re: String format - resolve placeholders names Denis McMahon <denismfmcmahon@gmail.com> - 2015-11-20 17:08 +0000
    Re: String format - resolve placeholders names Ervin Hegedüs <airween@gmail.com> - 2015-11-20 20:36 +0100

csiph-web