0

I have a prepared string, e.g. my_string = 'My name is {name}.'

and I have dictionary of kwargs, such as:

format_kwargs = {
    'name': 'John',
    ...
}

So that I can format the string in this manner: my_string.format(**format_kwargs)

That is all good. The problem is that I want to determine what keys are in the string, so that I do not calculate the kwargs needlessly. That is, I have a set of keywords used in these strings by default, but not all of them are used in all strings. They are basically regular messages shown to user, such as '{name}, you account was successfully created!'.

I want to do something like:

format_kwargs = {}

if 'name' in <my_string.keys>:
    format_kwargs['name'] = self.get_user().name
if '...' in <my_string.keys>:
    format_kwargs['...'] = some_method_...()

my_string.format(**format_kwargs)

How do I retrieve the keys?

EDIT:

a simple if 'name' in my_string does not work because that would also match something like {parent_name} or 'The name change was not successful.'

9
  • 1
    It is no problem to supply more keywords than present in the format string. Commented Oct 18, 2017 at 10:15
  • what is self.get_user()? Commented Oct 18, 2017 at 10:15
  • 1
    Are those values so very expensive to calculate that it's worth it? Commented Oct 18, 2017 at 10:16
  • 1
    What's wrong with if '{name}' in my_string:? However, as Jon implies, it may be more efficient to simply create the whole dict than to perform all those if tests. Commented Oct 18, 2017 at 10:16
  • 1
    Possible solutions can be found in this related question. In this particular case however, an alternative solution would be to implement a dict-like class that computes the values on demand. Commented Oct 18, 2017 at 10:18

1 Answer 1

0

Use string.Formatter

from string import Formatter
s = 'Hello {name}. Are you {debil_status}'
keys = [i[1] for i in Formatter().parse(s)]
print keys

>>> ['name', 'debil_status']
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.