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


Groups > comp.lang.python > #99170

Re: String format - resolve placeholders names

Path csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail
From Denis McMahon <denismfmcmahon@gmail.com>
Newsgroups comp.lang.python
Subject Re: String format - resolve placeholders names
Date Fri, 20 Nov 2015 17:08:21 -0000 (UTC)
Organization A noiseless patient Spider
Lines 40
Message-ID <n2nk25$mns$1@dont-email.me> (permalink)
References <20151120145227.GB13994@arxnet.hu> <mailman.3.1448034840.2291.python-list@python.org>
Mime-Version 1.0
Content-Type text/plain; charset=UTF-8
Content-Transfer-Encoding 8bit
Injection-Date Fri, 20 Nov 2015 17:08:21 -0000 (UTC)
Injection-Info mx02.eternal-september.org; posting-host="66ffcfa4470a58bcddbdcd1913f98ab4"; logging-data="23292"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+/b/1baBOcfvVttW5W9EBONRgBeAZEwEY="
User-Agent Pan/0.136 (I'm far too busy being delicious; GIT 926a150 git://git.gnome.org/pan2)
Cancel-Lock sha1:Em7uFv4K7dNsb8dh30BQuCfrYas=
Xref csiph.com comp.lang.python:99170

Show key headers only | 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