2013-09-27 51 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'本身外部重用。如果沒有,原則上任何第三方解決方案都應該像這個技巧一樣脆弱(或可靠)。 –