十六进制字符串的前导零

时间:2019-03-29 18:09:33

标签: python python-3.x

我以此读取UART端口:

print ("Attempt to Read")
readOut = serial_port.readline()
time.sleep(1)
in_hex = hex(int.from_bytes(readOut,byteorder='big')) 
print ("Reading: ", in_hex)

然后它给我输出例如喜欢:

Attempt to Read
Reading:  0x6011401011403

因此,在数字6之前缺少一个前导零。我无法找到一种方法来添加它,而无需在代码中指定整个字符串的长度(而且我不想这样做,因为字符串可以具有可变长度,例如0x056822)。你能帮忙吗?

2 个答案:

答案 0 :(得分:1)

当字符数为奇数时,您可以在0x之后插入零:

if len(in_hex)%2: in_hex = in_hex.replace("0x","0x0")

答案 1 :(得分:0)

如果将每个字节转换为两个字符,则可以保证偶数位数:

hexstr = ''.join(format(b,'02x') for b in bytesequence)

如果需要,只需"0x"开头。