检查要插入的字符串是否提供了预期的占位符
考虑这个虚构的 Python 函数:
def f(s):
# accepts a string containing placeholders
# returns an interpolated string
return s % {'foo': 'OK', 'bar': 'OK'}
如何检查字符串 s 是否提供了所有预期的占位符,如果没有,则使该函数礼貌地显示缺少的键?
我的解决方案如下。我的问题:有更好的解决方案吗?
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'}
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'}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一种方法可以使用 _formatter_parser 方法查看所有命名占位符:
对于“公共”方式:
There's a way to see all of the named placeholders using the _formatter_parser method:
For a "public" way: