0
a=10    
b=20    
res = (_("result is : %(first) , %(second)") %{'first' : a,'second' : b})    
print res

Could anyone explain the functionality of above code?

jamylak
  • 128,818
  • 30
  • 231
  • 230
Ganpat
  • 67
  • 1
  • 5
  • 7
    Do you happen to have a `from gettext import something as _` somewhere in your code? – Jon Clements Apr 08 '13 at 09:23
  • 1
    Why is everybody downvoting this? It seems like a legitimate question – jamylak Apr 08 '13 at 09:26
  • 4
    @jamylak: Because there is too little context here to determine what the question is *about*. Is it about the `_()` call, or about the `'' % {}` string formatting? (I didn't vote, but the OP has *not* explained what the problem is, really). – Martijn Pieters Apr 08 '13 at 09:28
  • @MartijnPieters I agree that it's too localized but it doesn't need a downvote and OP deserves an answer since the problem is simple enough – jamylak Apr 08 '13 at 09:29
  • i want to understand the (_( part . – Ganpat Apr 08 '13 at 09:30
  • 1
    Is this Django perhaps? They use `gettext`, see https://docs.djangoproject.com/en/dev/topics/i18n/translation/ – Martijn Pieters Apr 08 '13 at 09:33

2 Answers2

4

_ 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

Community
  • 1
  • 1
Paco
  • 4,520
  • 3
  • 29
  • 53
1

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)

halflings
  • 1,540
  • 1
  • 13
  • 34