2013-04-08 145 views
0
a=10  
b=20  
res = (_("result is : %(first) , %(second)") %{'first' : a,'second' : b})  
print res 

任何人都可以解釋上述代碼的功能嗎?請幫我理解這個python代碼

+7

你碰巧有一個'Gettext中的進口的東西作爲_'在你的代碼中的某個地方? – 2013-04-08 09:23:42

+1

爲什麼每個人都這樣?這似乎是一個合法的問題 – jamylak 2013-04-08 09:26:43

+4

@jamylak:因爲這裏沒有足夠的上下文來確定什麼是*關於*的問題。是關於'_()'調用還是關於'''%{}'字符串格式? (我沒有投票,但是OP沒有*真正解釋了問題所在)。 – 2013-04-08 09:28:04

回答

4

_通常是在gettext模塊的重新定義,它是一套幫助翻譯文本成多國語言工具:如下圖所示:

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

否則,當你在一個字符串中使用%(name)s,它是字符串格式。這意味着:「用我的字典格式化我的字符串」。這種情況下的字典是:{'first' : a,'second' : b}

雖然字符串的語法是錯誤的 - 它在括號後缺少s

你的代碼基本上打印:結果是:10,20 如果您修復丟失的s

欲瞭解更多信息,可以閱讀:Python string formatting: % vs. .format

1

此代碼不起作用:

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 

但除此之外,這似乎是一個簡單的文本格式化,使用舊式格式化與地圖。

你先寫使用語法%argument,然後你給它使用的語法包含此參數的值的地圖包含的參數字符串:

"This is an argument : %argument " % {'argument' : "Argument's value" }

儘量避免使用這一點,並使用format,而不是因爲它是更容易理解,更緊湊,更健壯:

"This is an argument : {} and this one is another argument : {} ".format(arg1, arg2)