Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #99156 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2015-11-21 02:06 +1100 |
| Last post | 2015-11-21 02:06 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: String format - resolve placeholders names Chris Angelico <rosuav@gmail.com> - 2015-11-21 02:06 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2015-11-21 02:06 +1100 |
| Subject | Re: String format - resolve placeholders names |
| Message-ID | <mailman.1.1448031974.2291.python-list@python.org> |
On Sat, Nov 21, 2015 at 1:52 AM, Ervin Hegedüs <airween@gmail.com> 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?
>
> There is a know method:
>
> d1 = {'who1': "Adam", 'what1': "ants"}
> try:
> s.format(**d1)
> except KeyError:
> print("keyword missing")
>
> (gives 'keyword missing' as result).
>
>
> But is there any other (direct) way, which keywords exists in
> string?
I think what you're asking for can be done using format_map with a
custom mapping object:
>>> class IdentiMap:
... def __init__(self):
... self.keys = []
... def __getitem__(self, key):
... self.keys.append(key)
...
>>> m = IdentiMap()
>>> "{who} likes {what}".format_map(m)
'None likes None'
>>> m.keys
['who', 'what']
Does that help?
ChrisA
Back to top | Article view | comp.lang.python
csiph-web