为什么是type(bytes())<'str'>

2024-10-01 04:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python相当陌生,我很欣赏它是一种动态语言。在我第一次编写python代码的大约30分钟内,我发现bytes类型的行为有点奇怪(至少可以这么说):

a = bytes()
print type(a)
// prints: <type 'str'>

在这里试试: http://ideone.com/NqbcHk

现在,docsstrings和{}的行为非常相似,除了.format和{}但我没想到它们是同一类型的。我要确保的是,我可以处理代码中的实际字节,并且不会发生强制/编码/解码。在

怎么回事?在


Tags: 代码com语言httpdocs类型bytestype
2条回答

你看到的是python3文档。在Python2中,bytesstr的别名,添加它是为了更容易地编写兼容代码(python2的str是一个字节字符串,而在python3中,str是python2中称为unicode)的别名。在

有关详细信息,请参见What’s New In Python 3.0。在

在python3.x中,bytes类型是新的。在python2.x中,作为兼容性填充程序,bytes是{}的一个简单别名。在

请在此处阅读更多信息:https://docs.python.org/2/whatsnew/2.6.html#pep-3112-byte-literals

Python 3.0 adopts Unicode as the language’s fundamental string type and denotes 8-bit literals differently, either as b'string' or using a bytes constructor. For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list.

The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.

相关问题 更多 >