我必须'解析'格式字符串才能提取变量。
E.g。
>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'
我设法通过使用正则表达式来实现:
re.findall(r"%\((\w+)\)", s)
但我想知道是否有内置解决方案(实际上Python会解析字符串以便对其进行评估!)。
答案 0 :(得分: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']