为了账号安全,请及时绑定邮箱和手机立即绑定

从包含字节数据的字符串中提取字节

从包含字节数据的字符串中提取字节

慕哥6287543 2022-05-24 13:10:53
我是 python 3 的新手,并试图从包含消息中字符串和字节的字节数组中提取消息。我无法从解码的字节数组中提取字节消息。首先,我解码字节数组。然后我对解码后的数组进行拆分。我在拆分数组时得到字符串值。我尝试使用bytes(v) for v in rest.split()函数尝试获取字节数组,然后对其进行解码,但无法。# The message chunk:chunk = b"1568077849\n522\nb'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'\n"# I split the chunk into sub categories for further processing:_, size, rest = (chunk.decode("utf-8")).split('\n', 2)# _ contains "1568077849"# size contains "522" # rest contains "b'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'"我应该能够解码其余变量(rest.decode(“utf-8”)),但由于它被存储为字符串,我很难弄清楚如何将其转换为字节和然后解码值。预期结果:l5:d4:auth53:ÙìH£ei6eli1eee
查看完整描述

2 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

这将打印您的最终结果:


chunk = b"1568077849\n522\nb'l5:d4:auth53:\xc3\x99\xc3\xac\x1fH\xc2\xa3ei6eli1eee'\n"


l1 = chunk.decode('utf-8').split()[2:]  # Initial decode

#  slice out the embedded byte string "b'  '" characters

l1_string = ''.join([x[:-2] if x[0] != 'b' else x[2:] for x in l1])

l1_bytes = l1_string.encode('utf-8')

l1_final = l1_bytes.decode('utf-8')


print('Results')

print(f'l1_string is {l1_string}')

print(f'l1_bytes is {l1_bytes}')

print(f'l1_final is {l1_final}')

Results

l1_string is l5:d4:auth53:ÙìH£ei6eli1ee

l1_bytes is b'l5:d4:auth53:\xc3\x99\xc3\xacH\xc2\xa3ei6eli1ee'

l1_final is l5:d4:auth53:ÙìH£ei6eli1ee


查看完整回答
反对 回复 2022-05-24
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

我能够通过这种方式获得预期的输出:


 _, size, rest = (chunk.decode("utf-8")).split('\n', 2)

 rest = bytes(rest.replace("b'", "").replace("'", ""), "utf-8").decode("unicode_escape")



查看完整回答
反对 回复 2022-05-24
  • 2 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号