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
6
  • 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. Commented Sep 4, 2019 at 18:05
  • How do you intend to handle something like {foo:04d} or {foo:{bar}{baz}}? What if the user enters {0}? Commented Sep 4, 2019 at 18:07
  • 2
    Maybe you could use something like string.Formatter? Commented Sep 4, 2019 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. Commented Sep 4, 2019 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. Commented Sep 4, 2019 at 18:20

1 Answer 1

4

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

This is much better than using regex, thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.