Python:从格式字符串中提取所有的占位符

3

我需要“解析”格式字符串以提取变量。

例如:

>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'

我通过使用正则表达式来实现了这个:

re.findall(r"%\((\w+)\)", s)

但我想知道是否有内置解决方案(实际上,Python会解析字符串以便于评估它!)。


1
我建议您改用新的Python 3字符串格式,其中string.Formatter和解析模块https://github.com/r1chardj0n3s/parse都可用。 - simonzack
请给出-1的原因:这将帮助我改进我的问题! - Don
1个回答

5

这似乎非常有效:

def get_vars(s):
    d = {}
    while True:
        try:
            s % d
        except KeyError as exc:
            # exc.args[0] contains the name of the key that was not found;
            # 0 is used because it appears to work with all types of placeholders.
            d[exc.args[0]] = 0
        else:
            break
    return d.keys()

提供给您:
>>> get_vars('%(code)s - %(description)s - %(age)d - %(weight)f')
['age', 'code', 'description', 'weight']

+1 这肯定是一个好的解决方案,但仍然使用了“技巧”;难道没有任何本地解决方案吗? - Don
1
我怀疑标准库中没有任何东西;但你可以看一下 CPython 源代码,了解 % 运算符是如何为 basestring 实现的,以及它是否可以从 basestring 之外重用。如果不行,任何第三方解决方案原则上都应该与此技巧一样脆弱(或可靠)。 - Erik Kaplun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接