python中bytes与bytearray以及encode与decode

一、encode与decode

1、bytes主要是给在计算机看的,string主要是给人看的

2、中间有个桥梁就是编码规则,现在大趋势是utf8

3、bytes对象是二进制,很容易转换成16进制,例如\x64

4、string就是我们看到的内容,例如'abc'

5、string经过编码encode,转化成二进制对象,给计算机识别

6、bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,\xc8就不是utf8识别的范围

例如encode使用:

"哈哈哈".encode("utf-8")    //执行结果为:b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
"哈哈哈".encode("gbk")   //执行结果为b'\xb9\xfe\xb9\xfe\xb9\xfe'

例如decode使用:

b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'.decode("utf-8")   //执行结果为:'哈哈哈'
b'\xb9\xfe\xb9\xfe\xb9\xfe'.decode("gbk")     //执行结果为:'哈哈哈'
>>> "哈哈哈".encode("utf-8")
b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
>>> "哈哈哈".encode("gbk")
b'\xb9\xfe\xb9\xfe\xb9\xfe'
>>> b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'.decode("utf-8")
'哈哈哈'
>>> b'\xb9\xfe\xb9\xfe\xb9\xfe'.decode("gbk")
'哈哈哈'

二、bytes 与 bytearray

bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。

#将数字转换为字节对象
bytes(1)     //转换后的值为:b'\x00'
#获取12个0填充的byte字节对象
bytes(12)       //值为:b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
#将数字数组转换为字节对象
bytes([1,2,3])   //值为:b'\x01\x02\x03'
#将字符串转换为字节对象
bytes("哈哈哈","utf-8")   //值为:b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
#将字符串转换为字节对象
bytes("哈哈哈","utf-8")  //值为:b'\xb9\xfe\xb9\xfe\xb9\xfe'
>>> bytes(1)
b'\x00'
>>> bytes(12)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes("哈哈哈","utf-8")
b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
>>> bytes("哈哈哈","gbk")
b'\xb9\xfe\xb9\xfe\xb9\xfe'

bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

#将数字转换为字节数组对象
bytearray(1)     //转换后的值为:bytearray(b'\x00')
#获取12个0填充的byte字节数组对象
bytearray(12)       //值为:bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
#将数字数组转换为字节数组对象
bytearray([1,2,3]   //值为:bytearray(b'\x01\x02\x03')
#将字符串转换为字节数组对象
bytearray("哈哈哈","utf-8")   //值为:bytearray(b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88')
#将字符串转换为字节数组对象
bytearray("哈哈哈","gbk")  //值为:bytearray(b'\xb9\xfe\xb9\xfe\xb9\xfe')
>>> bytearray(1)
bytearray(b'\x00')
>>> bytearray(12)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray("哈哈哈","utf-8")
bytearray(b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88')
>>> bytearray("哈哈哈","gbk")
bytearray(b'\xb9\xfe\xb9\xfe\xb9\xfe')

猜你喜欢

转载自www.cnblogs.com/liyuanhong/p/12167667.html
今日推荐