Get keys from template

后端 未结 7 932
忘掉有多难
忘掉有多难 2021-01-04 06:56

I would like to get a list of all possible keyword arguments a string template might use in a substitution.

Is there a way to do this other than re?

7条回答
  •  执念已碎
    2021-01-04 07:29

    If it's okay to use string.format, consider using built-in class string.Formatter which has a parse() method:

    >>> from string import Formatter
    >>> [i[1] for i in Formatter().parse('Hello {1} {foo}')  if i[1] is not None]
    ['1', 'foo']
    

    See here for more details.

提交回复
热议问题