欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python中bytearray,bytes转str的坑

程序员文章站 2024-03-23 17:29:40
...

先上干货。

python2

对于bytes

# coding=utf-8
testBytes_1 = b"abcd"
testBytes_2 = b"\x00\x01"

print "直接打印testBytes_1\t", testBytes_1
print "直接打印testBytes_2\t", testBytes_2
print "解码testBytes_1\t", testBytes_1.decode('utf-8')
print "编码testBytes_2\t", testBytes_2.encode('hex')

>>>直接打印testBytes_1 abcd
>>>直接打印testBytes_2 <0x00><0x01>
>>>解码testBytes_1     abcd
>>>编码testBytes_2     0001

bytes可以直接使用decode和encode函数进行转换

对于bytearray

# coding=utf-8
testBytes_1 = b"abcd"
testBytes_2 = b"\x00\x01"
testBytearray_1 = bytearray(testBytes_1)
testBytearray_2 = bytearray(testBytes_2)

print "直接打印testBytes_1\t", testBytearray_1
print "直接打印testBytes_2\t", testBytearray_2
print "解码testBytes_1\t", testBytearray_1.decode('utf-8')
temp = ""
for byte in testBytearray_2:
  t = hex(byte)[2:]
  if len(t) == 1:
    t = '0' + t
  temp += t
print "解码testBytes_2\t", temp

>>>直接打印testBytearray_1    abcd
>>>直接打印testBytearray_2    <0x00><0x01>
>>>编码testBytearray_1        abcd
>>>解码testBytearray_2        0001

bytearray没有encode函数,对于二进制的,如果执行testBytearray_2.encode('hex'),则报错AttributeError: 'bytearray' object has no attribute 'encode'

我能够想到的办法就是遍历bytearray,将每个byte转成十六进制字符。byte对python来讲,类型是数字,所以使用hex函数将数字转换为十六进制字符串。

python3

对于bytes

# coding=utf-8
import binascii

testBytes_1 = b'abcd'
testBytes_2 = b'\x00\x01'

print("直接打印testBytes_1\t", testBytes_1)
print("直接打印testBytes_2\t", testBytes_2)
print("解码testBytes_1\t", testBytes_1.decode('utf-8'))
print("编码testBytes_2\t", binascii.b2a_hex(testBytes_2).decode())

>>> 直接打印testBytes_1	 b'abcd'
>>> 直接打印testBytes_2	 b'\x00\x01'
>>> 解码testBytes_1	     abcd
>>> 编码testBytes_2	     0001

对于bytes,不像python2有encode方法,所以对于十六进制来说,只能使用binascii库,将bytes编为ascii码的bytes。如果就是要使用encode(),那么你将收获一条报错。

对于bytearray

testBytes_1 = b'abcd'
testBytes_2 = b'\x00\x01'
testBytearray_1 = bytearray(testBytes_1)
testBytearray_2 = bytearray(testBytes_2)

print("直接打印testBytearray_1\t", testBytearray_1)
print("直接打印testBytearray_2\t", testBytearray_2)
print("解码testBytearray_1\t", testBytearray_1.decode('utf-8'))
temp = ""
for byte in testBytearray_2:
	t = hex(byte)[2:]
	if len(t) == 1:
		t = '0' + t
	temp += t
print('解码testBytearray_1\t', temp)

>>> 直接打印testBytearray_1	 bytearray(b'abcd')
>>> 直接打印testBytearray_2	 bytearray(b'\x00\x01')
>>> 解码testBytearray_1	     abcd
>>> 解码testBytearray_1	     0001

这个和python2还是很像的。

搞清楚bytes和bytearray

为什么Python弱化类型?为什么Python弱化类型!为什么Python弱化类型!!!

因为类型的关系,在我debug查资料的时候,一直默认bytes和bytearray是一种东西,就像二哈和阿拉斯加雪橇犬,产品经理和二哈,并没有本质的区别。

具体可以看这篇博客

python bytes和bytearray、编码和解码 - 骏马金龙 - 博客园

最后再补充一点,这也是为啥我突然要搞清楚这个bytes和bytearray。

对于python2来讲,socket使用recv函数获取到的数据默认是str类型的;python3默认是bytes。这一点在官方socket api也有介绍,使用前请注意。

完事,睡觉!