Python:“str”做什么?
我在Django源代码中看到了这一点:Python:“str”做什么?,python,syntax,Python,Syntax,我在Django源代码中看到了这一点: description = _("Comma-separated integers") description = _("Date (without time)") 它有什么作用?我在Python 3.1.3中进行了尝试,但失败了: >>> foo = _("bar") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module
description = _("Comma-separated integers")
description = _("Date (without time)")
它有什么作用?我在Python 3.1.3中进行了尝试,但失败了:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo = _("bar")
NameError: name '_' is not defined
>>foo=uuu(“bar”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
foo=uuu(“bar”)
名称错误:未定义名称“\u1”
2.4.4中也没有运气:
>>> foo = _("bar")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
foo = _("bar")
NameError: name '_' is not defined
>>foo=uuu(“bar”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在顶层-
foo=uuu(“bar”)
名称错误:未定义名称“\u1”
这是怎么回事?这个名字和其他名字一样,是个普通的名字。语法
\uux)
使用参数x
调用名为\ucode>的函数。在这种情况下,它被用作Django定义的ugettext
的别名。此函数用于翻译字符串。从:
指定转换字符串:在Python代码中
标准翻译
使用函数ugettext()指定翻译字符串。按照惯例,将其作为较短的别名导入以保存键入
要在您自己的代码中使用。
,您可以使用如下导入:
from django.utils.translation import ugettext as _
在python中,符号\
只是一个变量名,在本例中,它似乎引用了一个函数或其他以字符串为参数的“可调用”函数。比如说
def myfun(strng):
return "input = " + strng
_ = myfun
description = _("Comma-separated integers")
需要注意的是,如果希望“makemessages”检测字符串,则不能选择所需的任何别名。这通常用于将字符串标记为GNU gettext的可翻译字符串。如下所示: