我需要“解析”格式字符串以提取变量。
例如:
>>> s = "%(code)s - %(description)s"
>>> get_vars(s)
'code', 'description'
我通过使用正则表达式来实现了这个:
re.findall(r"%\((\w+)\)", s)
但我想知道是否有内置解决方案(实际上,Python会解析字符串以便于评估它!)。
我需要“解析”格式字符串以提取变量。
例如:
>>> 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']
%
运算符是如何为 basestring
实现的,以及它是否可以从 basestring
之外重用。如果不行,任何第三方解决方案原则上都应该与此技巧一样脆弱(或可靠)。 - Erik Kaplun
string.Formatter
和解析模块https://github.com/r1chardj0n3s/parse都可用。 - simonzack