Python中的序列类型有bytes和bytearray。
二进制序列类型的用法比较少见,是python中少用的一种序列类型,对于二进制序列类型,大家基本了解即可。
bytes二进制序列类型
指定长度的零填充字节对象: bytes(3)
二进制字符串对象:bytes(b'abc')
bytearray二进制数组
指定长度的零填充字节对象: bytearray(3)
二进制字符串对象:bytearray(b'abc')
实例:
print(type("ffff")) # 字符串类型
print(type(b"ffff")) # 字节类型
# bytes是byte的序列,字符串是字符的序列
# str---》bytes
s1 = "中"
b1 = s1.encode('utf-8') # 编码(encode)
print(b1)
# bytes--->str
s2 = b1.decode("utf-8") # 解码(decode)
print(s2)
输出结果:
b'\xe4\xb8\xad'
中
# 拓展
# str---》bytes
s = '杨斯浩'
b1 = bytes(s, encoding='utf-8') #utf-8:3个字节(3bytes)表示一个汉字
b2 = bytes(s, encoding='GBK') #GBK使用两个字节(2bytes)表示一个汉字
print(b1)
print(b2)
# bytes--->str
s1 = str(b1, encoding='utf-8')
s2 = str(b2, encoding='gbk')
print(s1)
print(s2)
输出结果:
b'\xe6\x9d\xa8\xe6\x96\xaf\xe6\xb5\xa9'
b'\xd1\xee\xcb\xb9\xba\xc6'
杨斯浩
杨斯浩
解析:utf-8:3个字节(3bytes)表示一个汉字,GBK使用两个字节(2bytes)表示一个汉字,所以“杨斯浩”3个汉字,utf-8 需要9个字节,GBK 需要6个字节。
# bytearray
s1 = "你好,韦梅"
b1 = bytearray(s1.encode('utf-8'))
print(b1)
print(type(b1))
print(b1.decode('utf-8'))
b1[:6] = bytearray("美丽", encoding="utf-8")
print(b1)
print(b1.decode('utf-8'))
输出结果:
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe9\x9f\xa6\xe6\xa2\x85')
你好,韦梅
bytearray(b'\xe7\xbe\x8e\xe4\xb8\xbd\xef\xbc\x8c\xe9\x9f\xa6\xe6\xa2\x85')
美丽,韦梅
解析:"你好,韦梅"是5个字,所以utf-8需要15个字节表示。
编制by伟森leung 喜欢本文章的可以请关注伟森leung,后续有更多python方面的知识分享。
标签: bytes、bytearray的用法, python教程