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
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.
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")
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))
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
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