Python string formatting with keyword arguments
You can expand the dictionary by the named parameters
a = {'test': 'testing'}
b = "this is a {test}".format(**a)
print b
output: this is a testing
**
before the dictionary forces you to pass a parameter to a method that has a name that matches the key and a value that matches the value in the dictionary.
Now looking at your code and what you are trying to achieve, you are using two dictionaries. Therefore, you need to format the string twice.
a={'x':'test'}
b="this is a {{{x}}}".format(**a)
print b
print b.format(**{'test':'testing'})
output:
this is {test}
this testing
The first format creates a new named placeholder with the key value x. The second format will fill the owner's seat.
source to share
You have more trouble with your code than you say. The final is missing in the line "
, but it is also not clear what you are trying to do. What's for a
for?
What you need to do is put the key in parentheses, for example:
b="this is a %(test)s"
Or if you want to get x
from a
and then expand, you need to do something like:
b="this is a %%(%(x)s)s" % a
This will expand x
in and result in the line in the first example. I used double percent to avoid the percent sign.
source to share
How about using format
:
>>> a = {'x': 'test'}
>>> print("this is a {0[x]}".format(a))
this is a test
How to use format
:
{! Convertflag: formatspec}
formatspec:
[[fill] alignment] [sign] [#] [0] [width] [. Precision] [TypeCode]
I'll give you an example:
>>> import sys
>>> print("I'm using python {0.version}".format(sys))
I'm using python 2.7.9 (default, Mar 31 2015, 09:35:58)
[GCC 4.8.1]
>>> print("Hello, {name}".format(name="lord63"))
Hello, lord63
>>> print("{0}, {1}, {0}".format("one", "two"))
one, two, one
>>> print("The fifth: {0[4]}".format(range(1,6)))
5
>>> print("I'm {0[name]}".format(dict(name="lord63", age=20)))
I'm lord63
source to share