Function to get list of all identifiers in String

2019-08-02 00:51发布

For standard library string template in Python, is there a function to get a list of all identifiers?

For example, with the following xml file:

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

the function will return something like PrimaryKey, orientation

1条回答
We Are One
2楼-- · 2019-08-02 01:43

You can use 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']
查看更多
登录 后发表回答