从字符串中提取模板替换对象

2024-05-16 07:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们遇到这样的情况:

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

有没有办法提取这样的列表?你知道吗

['experiment1', 'experiment2']

谢谢!你知道吗


Tags: andtest列表stringwith情况办法experiment2
2条回答

使用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']

相关问题 更多 >