【Python3数据处理】数据转换 bytes/string/ASCII/GBK...

Python3 应用在做数据解析时,常常用到的数据类型是:字节,字符串,列表,字典(转json)
数据编码格式不同,数据存入的字节数组也会有所不同。

常用的数据编码格式,ASCII码,GBK编码,UTF8编码


数据转换参考示例

以下示例仅供参考,性能高低以实际测试情况为准,这里只考虑能否实现数据转换

1、字节(bytes)转字符串(str)

rec_msg = b'\x12\x55\xaa\xFF\x55\x34'
out_s = ''  
for i in range(0, len(rec_msg)):     # 获取字节数组字数据,注意引号 ' ' 之间有一个空格
    out_s = out_s + ' ' + (hex(int(rec_msg[i]))).upper()[2:].zfill(2)
    
print(out_s)    # >>> 12 55 AA FF 55 34

转换原理解析:分离出byte,转为int(), 再hex()转回16进制数后截取0x前缀,再遍历拼接成字符串

2、字符串(str)转为字节数组

hex_string = '01 02 27 11 00 08'            # 模拟请求读取DISCRETE信息的指令(未加crc值)
heartbeat = bytearray.fromhex(hex_string)
print(heartbeat)    # >>> bytearray(b"\x01\x02\'\x11\x00\x08")

3、int转为16进制字符串

hex(10)  # >> 0xa, type=str

4、16进制字符串转为int

int(hex(12), 16)    # 12
int('FF', 16)       # 255
int('FFEF', 16)     # 65519

5、16进制字符串 / int 转为2进制字符串

bin(int('FF', 16))     # >>> '0b11111111'
bin(0)[2:].zfill(8)    # >>> '00000000'

6、列表转为字符串

register_list = [1, 2, 3, 4,]
str_set = ''
for i in range(len(register_list)):
    str_set = str_set + register_list[i] + ' '

7、按空格截取字符串转到列表

out_s = '12 22 34 45 56'
out_s.split()    # 按空格截取字符串转到列表里面
# >>> ['12', '22', '34', '45', '56']

8、GBK编码格式的字符串(中文)转为 bytes 和16进制字符串

GBK编码: ( 1个中文对应2个byte)

a = '与'
a.encode('GBK')         # b'\xd3\xeb'
type(a.encode('GBK'))   # <class 'bytes'>

print('{}'.format(a.encode('GBK')).replace("b'\\x", '').replace('\\x', '').replace("'", '').strip().upper())
# 'D3EB'

9、bytes / bytearray / 16进制字符串 转为GBK编码的字符串(中文)

a = b'\xbf\xc6'             # bytes
print(a.decode('GBK'))      # '科'


b = 'bfc6 bfc6'             # bytes
b = bytearray.fromhex(b)    # bytearray
c = b.decode('GBK')         # str() 字符串(中文)
print('c:', c)              #  c: 科科

10、UTF-8编码格式也使用相同的方法转换

a = '中国'
b = a.encode('utf-8')      # b'\xe4\xb8\xad\xe5\x9b\xbd'

d = b'\xe4\xb8\xad\xe5\x9b\xbd'
d.decode('utf-8')          # '中国'

11、ASCII码转换

a = 't'
ord(a)         # 116
hex(ord(a))    # '0x74'


chr() 可以直接用16进制数或者 int 转换为对应的ASCII码字符
a = 0x30
chr(a)         # '0'
chr(48)        # '0'

12、8进制字符串 / byte 转换

oct(10)           # '0o12'
int(b'0o12', 8)   # 10
int('12', 8)      # 10

13、交叉转换,如既有GBK编码和ASCII编码的字符串转为16进制字符串

❌错误示例

a = 'Python3数据转换test'
a.encode('GBK')    # b'Python3\xca\xfd\xbe\xdd\xd7\xaa\xbb\xbbtest'

如上,单纯使用GBK编码不能将非中文字符转为对应的16进制的byte,
此时,可以将字符串拆分出来,一个一个转换

lst = []
for i in range(len(a)):
    lst.append(hex(ord(a[i]))[2:])
lst    # ['50', '79', '74', '68', '6f', '6e', '33', '6570', '636e', '8f6c', '6362', '74', '65', '73', '74']

可以发现ord()转换后,中文占用2个字节,英文占用1个字节

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章