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

Yun*_*Han 3 python stringtemplate

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

例如,使用以下 xml 文件:

<Text>Question ${PrimaryKey}:</Text>
<Text>Cheat: ${orientation}</Text>
Run Code Online (Sandbox Code Playgroud)

该函数将返回类似的内容PrimaryKey, orientation

Pad*_*ham 5

您可以使用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']
Run Code Online (Sandbox Code Playgroud)