Check if a string to interpolate provides expected placeholders
Consider this fictitious Python function:
def f(s):
# accepts a string containing placeholders
# returns an interpolated string
return s % {'foo': 'OK', 'bar': 'OK'}
How can I check that the string s provides all the expected placeholders, and if not, make the function politely show the missing keys?
My solution follows. My question: is there a better solution?
import sys
def f(s):
d = {}
notfound = []
expected = ['foo', 'bar']
while True:
try:
s % d
break
开发者_JAVA技巧 except KeyError as e:
key = e.args[0] # missing key
notfound.append(key)
d.update({key: None})
missing = set(expected).difference(set(notfound))
if missing:
sys.exit("missing keys: %s" % ", ".join(list(missing)))
return s % {'foo': 'OK', 'bar': 'OK'}
There's a way to see all of the named placeholders using the _formatter_parser method:
>>>> y="A %{foo} is a %{bar}"
>>>> for a,b,c,d in y._formatter_parser(): print b
foo
bar
For a "public" way:
>>>> import string
>>>> x = string.Formatter()
>>>> elements = x.parse(y)
>>>> for a,b,c,d in elements: print b
精彩评论