python中,怎么样把特定的字符串转为二进制序列?

2025-03-13 08:24:26
推荐回答(2个)
回答1:

只是要在字符串的基础上每隔2个字符加个间隔符号吗?

string = "3e210925041f000000a0010112008289125ba0000000"
temp_list = []
for index,item in enumerate(list(string)):
    temp_list.append(item.upper())
    if (index+1)%2 == 0:
        temp_list.append("  ")
    print(''.join(temp_list))

3E  21  09  25  04  1F  00  00  00  A0  01  01  12  00  82  89  12  5B  A0  00  00  00

回答2:

如果是需要pack字符串后,再使用socket进行发送的话,这样应该就可以了

import struct
str1='3e210925041f000000a0010112008289125ba0000000'
sdata=struct.pack('%ds'%len(str1),str1)
...
s.send(sdata)