Python 字符串 "Modifiers"

标签 python django

在 python 字符串前面调用的这些“修饰符”是什么?我不明白这些是干什么用的。另外,由于我不知道它们叫什么,所以我不知道要搜索什么来了解它们(或其他可用的信息,如果有的话)。

在这个例子中,返回字符串前面的“u”代表什么?

 def __unicode__(self):
        return u'title: %s, text: %s, created:%s, tags: %s' % (self.title, self.text, self.created, self.tags)

在这个 django URL 示例中,“r”代表什么?

urlpatterns = patterns('',
    (r'^admin/',include(admin.site.urls)),
)

我正在学习 python 和 django,我在示例中看到了这些,但没有解释它们代表什么。

最佳答案

'r' 表示一个原始字符串,它改变了转义行为。这对于正则表达式很有用,可以使它们更易于阅读。 'u' 表示它是一个 Unicode 字符串。他们被称为 string literal prefixes .

来自文档:

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences. A prefix of 'u' or 'U' makes the string a Unicode string. Unicode strings use the Unicode character set as defined by the Unicode Consortium and ISO 10646. Some additional escape sequences, described below, are available in Unicode strings. A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C.

关于Python 字符串 "Modifiers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9810589/

相关文章:

python - Python 中的 pretty-print 格式问题

python - 从列表中填充字典值

django manytomany模型关系在对象创建时崩溃管理

python - 找不到在 Mac OS X 上安装 python-dev 的方法

python - 可以在Python的日期时间模块上仅指定年份吗?

python - 正则表达式非贪婪精确匹配

javascript - 从附加元素调用 javascript

python - Django 中的 ModelForms 与 ManyToMany 关系模型

python - 如何在Elasticsearch中索引对象列表?

python - 你能编写一个针对任意状态的 django-fsm 转换吗?