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
_
通常是gettext
模块的重新定义,这是一组帮助将文本翻译成多种语言的工具:如下所示:http://docs.python.org/2/library/gettext.html
否则,当您在字符串中使用
%(name)s
时,它将用于字符串格式化。意思是:“用这本字典格式化我的字符串”。本例中的字典是:{'first' : a,'second' : b}
但是字符串的语法是错误的-它缺少括号后面的
s
。你知道吗你的代码基本上是打印出来的:结果是:10,20 如果修复丢失的
s
有关更多信息,请阅读:Python string formatting: % vs. .format
此代码无效:
但另外,这看起来像是一个简单的文本格式,使用旧式的地图格式。你知道吗
首先使用语法
%argument
编写一个包含参数的字符串,然后使用以下语法为其提供一个包含此参数值的映射:"This is an argument : %argument " % {'argument' : "Argument's value" }
尽量避免使用此选项,而是使用
format
,因为它更容易理解、更紧凑、更健壮:"This is an argument : {} and this one is another argument : {} ".format(arg1, arg2)
相关问题 更多 >
编程相关推荐