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.'