python除了 bytes字节序列 之外,还有bytearray可变的字节序列,具体区别在哪呢?顾名思义,前者是不可变的,而后者是可变的!具体本文会有详细的讲解!
# 1.定义空的字节序列bytearray
bytearray() -> empty bytearrayarray
# 2.定义指定个数的字节序列bytes,默认以0填充,不能是浮点数
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
# 3.定义指定内容的字节序列bytes
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
# 4.定义指定内容的字节序列bytes
bytearray(string, encoding[, errors]) -> bytearray
# 5.定义指定内容的字节序列bytes,只能为int 类型,不能含有float 或者 str等其他类型变量
bytearray(iterable_of_ints) -> bytearray
返回值:返回一个新的可变字节序列,可变字节序列bytearray有一个明显的特征,输出的时候最前面会有一个字符b标识,举个例子:
b'\x64\x65\x66'
b'i love you'
b'shuopython.com'
凡是输出前面带有字符b标识的都是字节序列bytes;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:何以解忧
@Blog(个人博客地址): https://www.codersrc.com/
@File:python_bytearray.py
@Time:2020/2/26 21:25
@Motto:不积跬步无以至千里,不积小流无以成江海,程序人生的精彩需要坚持不懈地积累!
"""
if __name__ == "__main__":
# 定义空的字节序列bytearray
b1 = bytearray()
print(b1)
print(type(b1))
print("***"*20)
# 定义指定个数的字节序列bytes,默认以0填充,不能是浮点数
b2 = bytearray(10)
print(b2)
print(type(b2))
print("***" * 20)
# 定义指定内容的字节序列bytes
b3 = bytes('abc', 'utf-8')
print(b3)
print(type(b3))
print("***" * 20)
# 正常输出
b1 = bytearray([1, 2, 3, 4])
>> > b'\x01\x02\x03\x04'
# bytes字节序列必须是 0 ~ 255 之间的整数,不能含有float类型
b1 = bytearray([1.1, 2.2, 3, 4])
>> > TypeError: an integer is required
# bytes字节序列必须是 0 ~ 255 之间的整数,不能含有str类型
b1 = bytearray([1, 'a', 2, 3])
>> > TypeError: an integer is required
# bytes字节序列必须是 0 ~ 255 之间的整数,不能大于或者等于256
b1 = bytearray([1, 257])
>> > ValueError: bytes must be in range(0, 256)
输出结果:
bytearray(b'')
<class 'bytearray'>
************************************************************
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
<class 'bytearray'>
************************************************************
b'abc'
<class 'bytes'>
************************************************************
if __name__ == "__main__":
# bytes不可变字节序列
b1 = b"abcd"
for i in b1:
print(i,end=" ")
print()
b1[0] = "A"
输出结果:
97 98 99 100
Traceback (most recent call last):
File "E:/Project/python/python_project/untitled10/123.py", line 22, in <module>
b1[0] = "A"
TypeError: 'bytes' object does not support item assignment
if __name__ == "__main__":
# bytearray可变字节序列
b1 = b"abcd"
b2 = bytearray(b1)
print("修改之前:",b2)
b2[0] = 65
print("修改之后:", b2)
输出结果:
修改之前: bytearray(b'abcd')
修改之后: bytearray(b'Abcd')