Python字符串“修饰符”

问题描述 投票:0回答:4

这些“修饰符”在python字符串的正面上是什么? 我不明白这些用途。 另外,由于我不知道它们是什么,所以我不知道该搜索什么来了解它们(或其他可能有可能可用的)。

在此示例中

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字面的前缀
python django
4个回答
13
投票

文档: sring文字可以选择用字母“ r”或“ r”前缀;这样的字符串称为原始字符串,并使用不同的规则来解释后斜线逃脱序列。 “ U”或“ U”的前缀使字符串成为Unicode字符串。 Unicode字符串使用Unicode Consortium和ISO 10646定义的Unicode字符集。下面描述的一些附加的逃生序列可在Unicode字符串中获得。 Python 2中忽略了“ B”或“ B”的前缀;这表明字面形式应成为python 3中的字面字面字面的字体(例如,当用2to3自动转换代码时)。 A“ U”或“ B”前缀之后可能是“ R”前缀。 除非存在“ r”或“ r”前缀,否则字符串中的逃生序列是根据与标准C使用的规则相似的规则来解释的。

python 2和Python 3之间的不同之处:

python 2:

"hello" # Normal string (8-bit characters) u"hello" # Unicode string r"hello" # Raw string --> Backslashes don't need to be escaped b"hello" # treated like normal string, to ease transition from 2 to 3

Python3:

"hello" # Unicode string b"hello" # Bytes object. Not a string! r"hello" # Raw string --> Backslashes don't need to be escaped u"hello" # Python 3.3, treated like Unicode string, to ease transition from 2 to 3

3
投票

those称为字符串文字:

Http://docs.python.org/reference/lexical_analysis.html#string-literals

例,r''是原始的,不会有相同的逃脱

使用文档,路加福音:

2
投票

U= Unicode字符串(每个项目代表Unicode

代码点


-4
投票

B/no prefix =字节字符串(每个项目都是字节)。请注意,在Python 3中,没有前缀表示Unicode字符串。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.