我必须’解析’格式字符串才能提取变量.
例如.
>>> s = "%(code)s - %(description)s" >>> get_vars(s) 'code','description'
我设法通过使用正则表达式来做到这一点:
re.findall(r"%\((\w+)\)",s)
但我想知道是否有内置的解决方案(实际上Python会解析字符串以便对其进行评估!).
解决方法
这似乎很有效:
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']