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

Don*_*Don 4 regex parsing string-formatting python-2.x

我必须'解析'格式字符串才能提取变量.

例如

>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'
Run Code Online (Sandbox Code Playgroud)

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

re.findall(r"%\((\w+)\)", s)
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有内置的解决方案(实际上Python会解析字符串以便对其进行评估!).

Eri*_*lun 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()
Run Code Online (Sandbox Code Playgroud)

给你:

>>> get_vars('%(code)s - %(description)s - %(age)d - %(weight)f')
['age', 'code', 'description', 'weight']
Run Code Online (Sandbox Code Playgroud)