Verbal_Kint Verbal_Kint - 1 year ago 92
Python Question

retrieve expected key name when formatting a string with .format

How can I retrieve the expected format key name from a string?

Lets say I have:

"This string expects {expected}"

If I input the wrong key name python throws a KeyError showing the expected name.

"This string expects {expected}".format(whoops="wrong key")
KeyError: 'expected'

Is there a way to test for this without regex or (ugh) purposely throwing the KeyError? I've looked over the string documentation but nothing jumped out at me.

Edit 1:

I do not want to suppress the error, nor do I want to silently fill it with None/empty string. I want to use the expected keyname to properly format the string.

I could rework it upstream by mapping the strings to the keyname in a dict, but was hoping to avoid that if there is a way to find this after the fact.

Regex would be a good solution, but at this point I am just curious more than anything.

Answer Source

You can use Formatter.parse like that:

>>> s="{a} {b} {c}"
>>> list(string.Formatter.parse("",s))
[('', 'a', '', None), (' ', 'b', '', None), (' ', 'c', '', None)]
>>> [t[1] for t in string.Formatter.parse("",s)]
['a', 'b', 'c']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download