假設我們有這樣的情況:從字符串中提取一個模板替換對象
>>> a = "test string with %(experiment1)s and %(experiment2)s"
有沒有一種方法來提取這樣的名單?
['experiment1', 'experiment2']
謝謝!
假設我們有這樣的情況:從字符串中提取一個模板替換對象
>>> a = "test string with %(experiment1)s and %(experiment2)s"
有沒有一種方法來提取這樣的名單?
['experiment1', 'experiment2']
謝謝!
使用regex
:
>>> import re
>>> a = "test string with %(experiment1)s and %(experiment2)s"
>>> re.findall(r'%\((.*?)\)', a)
['experiment1', 'experiment2']
您也可以欺騙Python的格式化程序爲尋找的鑰匙給你:
class MyDict(dict):
def __missing__(self, key):
return self.setdefault(key, "")
d = MyDict()
dummy = "test string with %(experiment1)s and %(experiment2)s" % d
print d.keys()
打印
['experiment1', 'experiment2']
+1學到了新東西。 –
+1非常有趣的解決方案!謝謝! –
的感謝!它完美的作品! –