How to get the variable names from the string for the format() method

后端 未结 5 1749
傲寒
傲寒 2020-12-18 07:32

Lets say I have this line:

\"My name is {name}\".format(name=\"qwerty\")

I know that the variable name is name and so I can f

5条回答
  •  一生所求
    2020-12-18 07:51

    You can parse the format yourself with the string.Formatter() class to list all references:

    from string import Formatter
    
    names = [fn for _, fn, _, _ in Formatter().parse(yourstring) if fn is not None]
    

    Demo:

    >>> from string import Formatter
    >>> yourstring = "My name is {myname}"
    >>> [fn for _, fn, _, _ in Formatter().parse(yourstring) if fn is not None]
    ['myname']
    

    You could subclass Formatter to do something more fancy; the Formatter.get_field() method is called for each parsed field name, for example, so a subclass could work harder to find the right object to use.

提交回复
热议问题