13

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.

6 Answers 6

43

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.

Sign up to request clarification or add additional context in comments.

7 Comments

But now, how do i use names in the format method to get all the values?
@MichaelR: How were you planning to pair up the names with values? You can always use dict(zip(names, values)) to create a dictionary, provided you know many values you need to provide.
@MichaelR: yourstring.format(**dict(zip(names, values))).
I wanted to use this: yourstring.format([(i,get_value(i)) for i in names]) but it gives me an error for some reason :-\
Right; you'd still have to build a dictionary; yourstring.format(**{i: get_value(i) for i in names}) if you are on Python 2.7 or newer.
|
4

Python 3.8 added an awesome solution for this using f-strings:

my_var = 123
print(f"{my_var = }")

Which will print

my_var = 123

2 Comments

what's happening here? is this a special syntax within f-strings? my_var = doesn't evaluate to a valid python expression, so it must be that string formatting is treating this construction differently. I had no idea this was possible!
looks documented here: docs.python.org/3/whatsnew/…
1

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

Comments

0
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

Comments

-1

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.