检查要插入的字符串是否提供预期的占位符 [英] Check if a string to interpolate provides expected placeholders
本文介绍了检查要插入的字符串是否提供预期的占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个虚构的 Python 函数:
def f(s):# 接受包含占位符的字符串# 返回一个内插字符串return s % {'foo': 'OK', 'bar': 'OK'}
如何检查字符串 s 是否提供了所有预期的占位符,如果没有,让函数礼貌地显示丢失的键?
我的解决方案如下.我的问题:有没有更好的解决方案?
导入系统定义 f(s):d = {}未找到 = []预期 = ['foo', 'bar']为真:尝试:% d休息除了 KeyError 为 e:key = e.args[0] # 缺少密钥notfound.append(key)d.update({key: None})缺失 = 设置(预期).差异(设置(未找到))如果丢失:sys.exit("缺少键:%s" % ", ".join(list(missing)))return s % {'foo': 'OK', 'bar': 'OK'}
解决方案
有一种方法可以使用 _formatter_parser 方法查看所有命名的占位符:
<预><代码>>>>>y="一个 %{foo} 是一个 %{bar}">>>>对于 y._formatter_parser() 中的 a,b,c,d:打印 b富酒吧对于公共"方式:
<预><代码>>>>>导入字符串>>>>x = string.Formatter()>>>>元素 = x.parse(y)>>>>对于元素中的 a、b、c、d:打印 bConsider 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'}
解决方案
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
这篇关于检查要插入的字符串是否提供预期的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文