假设我们遇到这样的情况:
>>> a = "test string with %(experiment1)s and %(experiment2)s"
有没有办法提取这样的列表?
['experiment1', 'experiment2']
谢谢!
答案 0 :(得分:4)
您还可以欺骗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 :(得分:0)
使用regex
:
>>> import re
>>> a = "test string with %(experiment1)s and %(experiment2)s"
>>> re.findall(r'%\((.*?)\)', a)
['experiment1', 'experiment2']