我已经知道python2.7中的r"string"
经常用于regex模式。我还看到了u"string"
的Unicode字符串。现在在python3中我们看到b"string"
。在
我在不同的源代码/问题中搜索过这些字符串,比如What does a b prefix before a python string mean?,但是很难看到Python中所有这些带有前缀的字符串的全貌,尤其是python2vs3。在
问题:您是否有一个经验法则来记住Python中带有前缀的不同类型的字符串?(或者可能是一个表,其中一列用于Python2,一列用于Python3?)在
NB:我读过一些问题和答案,但是我没有找到一个容易记住的与所有前缀/python2+3比较的方法
Python中实际上只有两种类型的字符串(或类似字符串的对象)。在
第一个是“Unicode”字符串,它是一个字符序列。 第二个是字节(或'bytestrings'),它是一个字节序列。在
第一种是Unicode规范中的一系列字母字符。 第二种是0到255之间的一系列整数,通常使用一些假定的编码(如ASCII或UTF-8)呈现为文本(这是在bytestream中编码Unicode字符的规范)。在
在python2中,默认的
"my string"
是bytestring。 前缀“u”表示“Unicode”字符串,例如u"my string"
。在在python3中,'Unicode'字符串成为默认值,因此
"my string"
相当于u"my string"
。 要获得旧的python2 bytestrings,需要使用前缀b“mystring”(在python3的最旧版本中没有)。在还有两个前缀,但它们不影响string对象的类型,只影响它的解释方式。 第一个是不解释转义字符(如\n或\t)的“raw”字符串。例如,原始字符串
r"my_string\n"
包含字面反斜杠和“n”字符,而"my_string\n"
在行尾包含一个换行符。在第二个是在python3的最新版本中引入的:带前缀“f”的格式化字符串。其中,大括号用于显示要解释的表达式。例如,字符串:
将被解释为
"my (1.5, avocado) string"
(其中逗号创建了一个元组)。当代码被读取时,这种解释会立即发生;随后字符串没有什么特别的地方。在最后,您可以使用多行字符串表示法:
^{pr2}$根据需要使用“r”或“f”说明符。在
在Python2中,如果没有使用前缀或只使用了“r”前缀,则它是bytestring;如果使用了“u”前缀,则它是Unicode字符串。在
在python3中,如果没有使用前缀,或者只使用了“r”、“f”和“u”的组合,则它是Unicode字符串。如果您使用了'b'前缀,那么它是一个bytestring。显然不允许同时使用“b”和“u”。在
从python文档中获取文本:https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
以及
所以:
python2中已经提供了r和b,就像许多其他语言一样(它们有时非常方便)。在
由于python2中的字符串文本不是unicode,因此创建u字符串是为了提供国际化支持。在python3中,u字符串是默认字符串,因此“…”在语义上与u“…”相同。在
最后,从中可以看出,f-string是python2中唯一不支持的字符串。在
from __future__ import unicode_literals
,这使得Python2几乎相同b-strings用于原始字节-不知道文本,而只是字节流。很少用作源代码的输入,通常是由于网络或低级代码读取二进制格式的数据、解包归档文件、使用加密库。在
通过
.encode
&;.decode
r-strings不是专门针对regex的,这是“原始”字符串。与常规字符串文本不同,r-string对转义字符没有任何特殊的含义。一、 普通字符串}。经常可以在两个地方看到原始字符串:
abc\n
长4个字符,最后一个字符是“newline”特殊字符。为了以文字形式提供它,我们使用了带\
的转义。对于原始字符串,r'abc\n'
是5个长度的字符串,最后两个字符是\
和{正则表达式模式-不要在模式中使用实际的特殊字符进行转义
windows系统的文件路径表示法,因为windows家族使用},而raw则更好:}
\
作为限定符,普通的字符串文字看起来像'C:\\dir\\file'
,或者{r'C:\dir\file'
和{另一个值得注意的是f-strings,它在python 3.6中作为一种简单而强大的格式化字符串的方式而出现:
f'a equals {a} and b is {b}'
将在运行时替换变量a
和{相关问题 更多 >
编程相关推荐