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

Suppose I have this line:

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

I know that the name of the variable is name , and so I can fill it out. But what if the word inside {} always changes, for example:

 "My name is {name}" "My name is {n}" "My name is {myname}" 

I want to be able to do this:

 "My name is {*}".format(*=get_value(*)) 

Where * is what was ever entered in {}

I hope that I understand.


EDIT:

 def get_value(var): return mydict.get(var) def printme(str): print str.format(var1=get_value(var1), var2=get_value(var2)) printme("my name is {name} {lastname}") printme("your {gender} is a {sex}") 

However, I cannot hardcode any of the variables inside the printme function.

+2
python
source share
4 answers

You can independently analyze the format of the string.Formatter() class to display all the links:

 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 can subclass Formatter to do something more fantastic; the Formatter.get_field() method is called for each syntax field name, for example, so the subclass can get complicated to find a suitable object to use.

+6
source share

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

 data = {'first_name': 'Monty', 'last_name': 'Python'} print('Hello {first_name}'.format(**data)) print('Hello {last_name}'.format(**data)) 
+1
source share

You can use a 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
source share

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
source share

All Articles