获取字符串模板(Python)中所有标识符列表的函数

时间:2015-05-23 22:20:00

标签: python stringtemplate

对于Python中的标准库string template,是否有一个函数来获取所有标识符的列表?

例如,使用以下xml文件:

<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>

该函数将返回PrimaryKey, orientation

之类的内容

1 个答案:

答案 0 :(得分:3)

您可以使用string.Formatter.parse

from string import Formatter

s="""<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>"""


print([ele[1] for ele in Formatter().parse(s) if ele[1]])
['PrimaryKey', 'orientation']