请帮我理解这个

2024-04-25 19:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人能解释一下以上代码的功能吗?你知道吗


Tags: 代码功能isresresultfirstprintsecond
2条回答

_通常是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

此代码无效:

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)

相关问题 更多 >