Function to get list of all identifiers in String Template (Python)

纵然是瞬间 提交于 2019-12-11 10:26:07

问题


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:


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


来源:https://stackoverflow.com/questions/30418132/function-to-get-list-of-all-identifiers-in-string-template-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!