2013-09-27 56 views
3

为了提取变量,我必须“解析”格式字符串。Python:从格式字符串提取所有占位符

E.g.

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

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

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

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

+1

我建议你使用新的Python 3字符串格式代替,其中两个'string.Formatter'和解析模块: https://github.com/r1chardj0n3s/parse可用。 – simonzack

+0

请给出-1的理由:它会帮助我改善我的问题! – Don

回答

4

这似乎是伟大的工作:

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'] 
+0

+1这当然是一个很好的解决方案,但仍然使用'技巧';没有任何本地解决方案? – Don

+1

我怀疑stdlib中有什么东西;您可以在CPython源代码中查看“basestring”实现了'%'运算符,以及它是否可以从'basestring'本身外部重用。如果没有,原则上任何第三方解决方案都应该像这个技巧一样脆弱(或可靠)。 –