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 fill it.
But what if the word inside the {}
always changes, like this:
"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 ever word was given inside the {}
Hope I was clear.
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}")
Having this, I can't hard code any of the variables inside printme
function.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With