10

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.

Michał Zaborowski
  • 3,911
  • 2
  • 19
  • 39
MichaelR
  • 969
  • 14
  • 36

6 Answers6

35

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • But now, how do i use `names` in the `format` method to get all the values? – MichaelR Apr 03 '14 at 07:22
  • @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. – Martijn Pieters Apr 03 '14 at 07:24
  • @MichaelR: `yourstring.format(**dict(zip(names, values)))`. – Martijn Pieters Apr 03 '14 at 07:24
  • I wanted to use this: `yourstring.format([(i,get_value(i)) for i in names])` but it gives me an error for some reason :-\ – MichaelR Apr 03 '14 at 07:32
  • `get_value()` is a method defined on the `Formatter` class; I was talking about a more complex setup where you subclass that class to have `get_value()` do something different in your overridden method. Read the `Formatter` documentation for more details. – Martijn Pieters Apr 03 '14 at 08:42
  • I ment my `get_value` method ive written – MichaelR Apr 03 '14 at 09:33
  • 1
    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. – Martijn Pieters Apr 03 '14 at 09:35
3

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
Flair
  • 2,609
  • 1
  • 29
  • 41
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
Nishant Nawarkhede
  • 8,234
  • 12
  • 59
  • 81
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
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
-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")
Mihai Zamfir
  • 2,167
  • 4
  • 22
  • 37
-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))
Matthias
  • 12,873
  • 6
  • 42
  • 48