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

谁能解释上述代码的功能?

4

2 回答 2

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

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

于 2013-04-08T09:28:41.253 回答
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)

于 2013-04-08T09:28:24.840 回答