字节数组和列表的区别 [英] Difference between bytearray and list
问题描述
bytearray
和例如 list
或 tuple
之间有什么区别?
顾名思义,bytearray
必须是一个带有byte
对象的array
.
在python中,似乎bytes
和str
被同等对待
那么,有什么区别呢?
另外,如果你打印一个bytearray
,结果很奇怪
它似乎转换了 chr(integer)
中的整数,对吗?bytearray
那么有什么用呢?
在某些方面你是对的:在 Python 2 中,bytes
是 str
类型的同义词.这是因为最初没有 bytes
对象,只有 str
和 unicode
(后者用于 unicode 字符串,即具有多个字节能力).当 Python 3 出现时,他们改变了整个字符串的东西,并使 unicode 成为默认的 Python 3 str
类型,并且他们添加了 bytes
作为原始字节序列的类型(使其等效到 Python 2 的 str
对象).
因此,虽然在 Python 3 中 str
和 bytes
有所不同,但 Python 2 中的相应类型是 unicode
和 str代码>.
现在让 bytearray
类型有趣的是它是可变的.上面的所有字符串和字节序列都是不可变的,因此每次更改时,您都在创建一个新对象.但是您可以修改 bytearray
对象,使它们在您需要修改序列中的单个字节的各种用途中变得有趣.
What is the difference between bytearray
and for example, a list
or tuple
?
As the name suggests, bytearray
must be an array
that carries byte
objects.
In python, it seems that bytes
and str
are treated equally
>>> bytes
<type 'str'>
So, what is the difference?
Also, if you print a bytearray
, the result is pretty weird
>>> v = bytearray([200, 201])
>>> print v
ÈÉ
It seems that it transforms the integer in chr(integer)
, is that right? What is the use of a bytearray
then?
You are correct in some way: In Python 2, bytes
is synonymous with the str
type. This is because originally, there was no bytes
object, there was only str
and unicode
(the latter being for unicode string, i.e. having multi-byte capabilities). When Python 3 came, they changed the whole string things and made unicode the default Python 3 str
type, and they added bytes
as the type for raw byte sequences (making it equivalent to Python 2’s str
object).
So while in Python 3 you differ between str
and bytes
, the corresponding types in Python 2 are unicode
and str
.
Now what makes the bytearray
type interesting is that it’s mutable. All string and byte sequences above are immutable, so with every change, you are creating a new object. But you can modify bytearray
objects, making them interesting for various purposes where you need to modify individual bytes in a sequence.
这篇关于字节数组和列表的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!