1

假设我们有这样的情况:

>>> a = "test string with %(experiment1)s and %(experiment2)s"

有没有办法提取这样的列表?

['experiment1', 'experiment2']

谢谢!

4

2 回答 2

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']
于 2013-08-20T21:13:12.543 回答
0

使用regex

>>> import re
>>> a = "test string with %(experiment1)s and %(experiment2)s"
>>> re.findall(r'%\((.*?)\)', a)
['experiment1', 'experiment2']
于 2013-08-20T20:51:19.437 回答