如果不重新编码字符串,则无法将解码的字符串附加到列表

2024-09-24 00:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的不知道如何在标题中表达这个问题,我认为仅仅显示我的代码就可以说明问题本身

import struct

thing1_to_pack = b'Hello World'
thing2_to_pack = 1982
thing3_to_pack = b'weeee123'

packed_thing = struct.pack('12si20s', 
  thing1_to_pack,
  thing2_to_pack,
  thing3_to_pack)

print(f'Packed thing is {packed_thing}\n')

unpacked_thing = struct.unpack('12si20s', packed_thing)

print(f'Unpacked thing is {unpacked_thing}\n')

listthing = []

for val in unpacked_thing:
  try:
    print(f'Adding {val.decode()} to the list\n')
    listthing.append(val.decode())
  except AttributeError as err:
    print(f'Adding {val} to the list\n')
    listthing.append(val)


print(f'Our final result is {listthing} !')

我希望最终的结果是

['Hello World', 1982, 'weeee123']

然而,我最终得到的是

['Hello World\x00', 1982, 
'weeee123\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']

我真的不知道该怎么办,我知道如何通过将12si20减少到11si8s来摆脱\x00,但是我使用这个的项目将有不同的大小,我需要能够将它们去掉

有人知道怎么做吗


Tags: tohelloworldisvalstructpackprint
1条回答
网友
1楼 · 发布于 2024-09-24 00:32:47

试着在你最后的print之前写下以下内容

listthing = [var.rstrip('\0')] for var in listthing]

这将从字符串的末尾删除所有讨厌的空字节

相关问题 更多 >