2

Given a string that uses named placeholders for formatting, is it possible to inspect what the names are dynamically?

>>> var = '''{foo} {bar} {baz}'''
# How to do this?
>>> for k in var.inspect_named_placeholders():
>>>     print(k)
foo
bar
baz
Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • 1
    Sounds like an X-Y problem. Why do you want that? You are providing the Y, with the assumption that it is the best solution for X. – Mad Physicist Sep 04 '19 at 18:05
  • How do you intend to handle something like `{foo:04d}` or `{foo:{bar}{baz}}`? What if the user enters `{0}`? – Mad Physicist Sep 04 '19 at 18:07
  • 2
    Maybe you could use something like [string.Formatter](https://stackoverflow.com/questions/14061724/how-can-i-find-all-placeholders-for-str-format-in-a-python-string-using-a-regex/14061832#14061832)? – DSM Sep 04 '19 at 18:08
  • @DSM. Good find. I didn't know that would be exposed, but it makes sense, given that this is python after all. – Mad Physicist Sep 04 '19 at 18:10
  • @MadPhysicist Sorry, I do not follow. My problem is that I want to extract the named placeholders from a string. `inspect_named_placeholders` was not my proposed solution and was only used to show an example of something I am looking for. `string.Formatter` as provided by juanpa.arrivillaga and DSM is perfect. – Matthew Moisen Sep 04 '19 at 18:20
  • @MatthewMoisen. I understood the problem and the question. I was just wondering if you had a broader purpose, and how you intend to handle the inevitable corner cases if not. – Mad Physicist Sep 04 '19 at 20:27

1 Answers1

3

Yes, you can use the built-in parser:

>>> var = '''{foo} {bar} {baz}'''
>>> import string
>>> formatter = string.Formatter()
>>> formatter.parse(var)
<formatteriterator object at 0x109174750>
>>> list(formatter.parse(var))
[('', 'foo', '', None), (' ', 'bar', '', None), (' ', 'baz', '', None)]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172