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

后端 未结 5 1746
傲寒
傲寒 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.

    0 讨论(0)
  • 2020-12-18 07:53

    Or an alternative is to use a function:

    def format_string(name):
        return "My name is {name}".format(name="qwerty")
    

    Then call it:

    format_string("whatever")
    
    0 讨论(0)
  • 2020-12-18 08:00

    If your data is in a dictionary (according to your edited question) then you can use the dictionary as a parameter for format.

    data = {'first_name': 'Monty',
            'last_name': 'Python'}
    
    print('Hello {first_name}'.format(**data))
    print('Hello {last_name}'.format(**data))
    
    0 讨论(0)
  • 2020-12-18 08:13

    You can use variable instead of name="querty"

    name1="This is my name";
    
    >>"My name is {name}".format(name=name1)
    

    Output:

    'My name is abc'
    

    Another example ,

    a=["A","B","C","D","E"]
    >>> for i in a:
    ...     print "My name is {name}".format(name=i)
    

    Output:

    My name is A
    My name is B
    My name is C
    My name is D
    My name is E
    
    0 讨论(0)
  • 2020-12-18 08:17
    def get_arg(yourstring):
        arg_list = []
        pin = False
        for ch in yourstring:
            if ch == "{":
                pin = True
            elif ch == "}":
                pin = False
                arg_list.append(text)
                text = ""
            elif pin:
                text +=ch
        return arg_list
    
    0 讨论(0)
提交回复
热议问题