Check if a string to interpolate provides expected placeholders

人走茶凉 提交于 2019-12-12 18:08:38

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/4839121/check-if-a-string-to-interpolate-provides-expected-placeholders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!