亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從包含字節數據的字符串中提取字節

從包含字節數據的字符串中提取字節

慕哥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 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號