将字节转换为列表

2024-10-02 18:20:34 发布

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

我对这类东西还不熟悉,所以如果它真的很简单的话,我很抱歉,我只是太愚蠢了

因此,我有一个包含一些字节的变量(不确定名称是否正确) 数据=b'red\x00XY\x001\x00168.93\x00859.07\x00'

我需要把它转换成一个列表。预期的输出类似于。 [“红色”、“XY”、“1”、“169.93”、“859.07”]

我该怎么做呢

谢谢你的帮助


Tags: 数据名称列表字节redxyx00红色
2条回答

这段代码可以帮助您理解您是否希望使用pop()函数获得完全相同的输出

data = 'red/x00XY/x001/x00168.93/x00859.07/x00'  # I change "/" mark from "\" because i'm  using Linux otherwise it will give error in Linux

new_list = []  # There is a variable that contain empty list

for item in data.split('/x00'):  # Here I use split function by default it splits variable where "," appears but in this case
    new_list.append(item)     # you need list should be separated by "/" so that's why I gave split('/x00') and one by list appended

print(new_list)```

我们可以使用以下行:

[x.decode("utf8") for x in data.split(b"\x00") if len(x)]

一部分一部分地进行:

  • x.decode("utf8")x将是一个字节字符串,因此我们需要通过“.decode”(“utf8”)将其转换为字符串
  • for x in data.split(b"\x00"):我们可以使用python内置的bytes.split方法将字节字符串按空字节分割,以获得单个字符串的数组
  • if len(x):这相当于if len(x) > 0,因为我们希望丢弃结尾的空字符串

相关问题 更多 >