二进制的数据的转换
1. 二进制类型/字节(bytes)
2. 其他数据转二进制 bytes(数据)
float类型数据不能直接转成二进制数据
print(bytes('li', encoding='utf-8')) # b'li'
print(bytes([1, 2])) # b'\x01\x02'
列表型可以转二进制,只能是数字
print(bytes())
list1 = [100, ‘abc’, 12.5]
print(bytes(str(list1), encoding=‘utf-8’)) # b"[100, ‘abc’, 12.5]"
3.二进制转字符串:
方法一:
str(数据, encoding ='utf-8')
字符串转二进制: 字符串.encode(encoding='utf-8')
t2 = str(bytes(str(list1), encoding='utf-8'), encoding='utf-8')
print(t2, type(t2)) # [100, 'abc', 12.5] <class 'str'>
t1 = eval(t2)
print(t1, type(t1)) # [100, 'abc', 12.5] <class 'list'>
t3 = t2.encode(encoding='utf-8')
print(t3) # b"[100, 'abc', 12.5]"
方法二:二进制数据.decode(encoding='utf-8)
b1 = t3.decode(encoding='utf-8')
print(b1, type(b1)) # [100, 'abc', 12.5] <class 'str'>