4

我必须“解析”一个格式字符串才能提取变量。

例如

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

我设法通过使用正则表达式来做到这一点:

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

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

4

1 回答 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']
于 2013-09-27T10:15:50.327 回答