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

后端 未结 5 1758
傲寒
傲寒 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 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))
    

提交回复
热议问题