Reputation: 1
I am havig some doubt regarding the string formatting expressions in python:
The general syntax of the string formatting expression is
%[keyname][flags][width][.precision]typecode
I am having couple of doubt in this and these are:
For example:
x="%(z)d is equal to" %{"z":1} # This expression gives me the required output.
but when I try this one:
x="%(z)d is equal to" %("z"=1) # Causes error. I am getting confused with this.
similarly when I use like this:
x="%(z)d is equal to" %dict("z"=1)
It also shows an error. Why?
Upvotes: 0
Views: 58
Reputation: 16942
Keyname means the name in parentheses, for example z
in %(z)d
. It is called keyname because "z"
is the dictionary key that will return the value you want substituted in your string, in this case 1
.
You are confusing two ways to specify a dictionary.
One is with braces { }
, for which the syntax is {"z": 1}
. You can specify the key (here z
) as a constant or as a variable and the variable can contain any hashable value: tuples qualify, lists don't, recursively.
So, as you have found out, this is valid:
x = "%(z)d is equal to" % {"z":1}
The other way is to call the dict
constructor, for which the syntax is dict(z=1)
. But here the key must be a valid Python identifier because in this syntax you are passing z
as a keyword parameter to dict()
.
In this syntax the equivalent of the first valid example is:
x ="%(z)d is equal to" % dict(z=1)
You are getting errors on the other lines because
("z"=1)
does not specify a dict
because it has neither {...}
nor a dict()
constructor call.
dict("z"=1)
is mixing up the first syntax (key is a constant, use { }
and colon instead) with the second syntax (key can't be a constant: it needs to be an identifier that you provide as a keyword parameter to the dict()
call).
Upvotes: 1