Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 751
MichaelR Avatar asked Apr 03 '14 07:04

MichaelR


People also ask

What is string format () used for?

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.

What is return by format () method?

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.

Where is the format () method used?

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.


1 Answers

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.

like image 186
Martijn Pieters Avatar answered Oct 13 '22 23:10

Martijn Pieters