将字符串转换为字节时遇到问题

Having Trouble converting a string to bytes

我正在尝试将字符串转换为字节,这就是我所做的。
我想通过串行发送一个 Modbus 协议并将其放在位串中:

tiger = '01' 
read = '03'
ac_val = '0031'
word = '0002'

code = tiger+read+ac_val+word
print(code)
010300310002

#now i want to put thist string in a bitstring with the function:

codeh = bytes.fromhex(code)
codeh = b'\x01\x03\x001\x00\x02 #This is what i got

但我期待:

codeh = b'\x01\x03\x00\x31\x00\x02

我不知道为什么输出是这样的。

它在输出中显示的是字节值的 ASCII 表示形式。十六进制 31 对应于 ascii 字符“1”。试试看演示:

bytes.fromhex('415343494921')

这是显示这些低值的图表:https://en.wikipedia.org/wiki/ASCII#Control_code_chart