实用技巧
列表推导式
# 升级版的for循环
# 遍历B中的每个元素i,可以在A处操作i
# 返回一个list
#
[A(i) for i in B]
数据类型转换
进制转换
1、bcd和string的相互转换
import binascii
b = b'\x12\x34'
s = binascii.b2a_hex(b).decode()
#b'\x12\x34'->'1234'
s = '1234'
b = binascii.a2b_hex(s)
#'1234'->b'\x124'=b'\x12\x34'
2、bytes和int的相互转换
# big 是大端 从左到右
b = b'\x12\x34'
n = int.from_bytes(b,byteorder='big',signed=False)
#b'\x12\x34'->4660
# little是小端 从右到左
b = b'\x12\x34'
n = int.from_bytes(b,byteorder='little',signed=False)
#b'\x12\x34'->13330
n = 4660
b = n.to_bytes(length=2,byteorder='big',signed=False)
#4660->b'\x12\x34'
n = 13330
b = n.to_bytes(length=2,byteorder='little',signed=False)
#13330->b'\x12\x34'
3、bytes和int[]的相互转换
b = b'\x12\x34'
n = []
for i in b[:]:
n.append(i)
#b'\x12\x34'->[12,34]
n = [12,34]
b = bytes(n)
#[12,34]->b'\x12\x34'
?4 bytes和hex字符串之间的相互转换。
>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>
?5 HEX转INT,INT转BYTE, BYTE转字符串
import sys
loginlidar = (0x02, 0x73, 0x4D, 0x4E, 0x20, 0x53, 0x65, 0x74, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x4D, 0x6F, 0x64, 0x65, 0x20, 0x30, 0x33, 0x20, 0x46, 0x34, 0x37, 0x32, 0x34, 0x37, 0x34, 0x34, 0x03)
b = bytes(loginlidar)
print(loginlidar)
print(len(b))
print(b.decode())
print(len(b.decode()))
'''
输出:
(2, 115, 77, 78, 32, 83, 101, 116, 65, 99, 99, 101, 115, 115, 77, 111, 100, 101, 32, 48, 51, 32, 70, 52, 55, 50, 52, 55, 52, 52, 3)
31
sMN SetAccessMode 03 F4724744
31
'''
控制台花样
# pip install termcolor
#
# 打印带有颜色的控制台
from termcolor import colored
print(colored(msg, 'green'))
|