bytearray()函数介绍
bytearray()函数是Python中的内置函数,用来创建可变字节数组。bytearray对象可以替代字节字符串,它支持可变操作,并且可以修改它的内容。
bytearray()函数使用方法
bytearray()函数接受一个参数,参数可以是整数、字符串、字节对象或者可迭代对象。
# 使用整数创建字节数组
b = bytearray(10)
print(b)
# 使用字符串创建字节数组
b = bytearray("Hello World!", 'utf-8')
print(b)
# 使用字节对象创建字节数组
b = bytearray(b"Hello World!")
print(b)
# 使用可迭代对象创建字节数组
b = bytearray([1, 2, 3, 4])
print(b)
bytearray对象支持像字节字符串一样的操作,比如索引、切片、连接、重复等。
# 索引
b = bytearray("Hello World!", 'utf-8')
print(b[0])
# 切片
print(b[2:5])
# 连接
b1 = bytearray("Hello", 'utf-8')
b2 = bytearray("World!", 'utf-8')
b3 = b1 + b2
print(b3)
# 重复
b = bytearray("Hello", 'utf-8')
print(b*3)
bytearray对象还支持更新操作,比如更新某一位的值,或者更新某一段字节的值。
# 更新某一位的值
b = bytearray("Hello World!", 'utf-8')
b[0] = ord('h')
print(b)
# 更新某一段字节的值
b[2:5] = b"abc"
print(b)
bytearray()函数创建的可变字节数组可以用来替代字节字符串,它支持像字节字符串一样的操作,而且还支持可变操作,可以修改它的内容。