a=10
b=20
res = (_("result is : %(first) , %(second)") %{'first' : a,'second' : b})
print res
Could anyone explain the functionality of above code?
a=10
b=20
res = (_("result is : %(first) , %(second)") %{'first' : a,'second' : b})
print res
Could anyone explain the functionality of above code?
_
is usually the redefinition of the gettext
module, which is a set of tools that helps translating text into many languages: As shown here:
import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print _('This is a translatable string.')
http://docs.python.org/2/library/gettext.html
Otherwise, when you use %(name)s
in a string, it's for string formatting. It means: "format my string with this dictionary". The dictionary in this case is: {'first' : a,'second' : b}
The syntax of your string is wrong though - it's missing the s
after the brackets.
Your code basically prints: result is : 10 , 20
If you fix the missing s
For further information, you can read this: Python string formatting: % vs. .format
This code doesn't work :
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> b = 20
>>> res = (_("result is : %(first) , %(second)") %{'first' : a,'second' : b})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
But otherwise, this seems like a simple text formating, using old style formating with maps.
You first write a string containing arguments using the syntax %argument
and then you give it a map containing this argument's value using this syntax :
"This is an argument : %argument " % {'argument' : "Argument's value" }
Try to avoid using this and use format
instead as it's easier to understand, more compact and more robust:
"This is an argument : {} and this one is another argument : {} ".format(arg1, arg2)