首页 > 解决方案 > 将一串字节数组转换为字节数组

问题描述

我有一串字节数组,我想在 python 3 中将其转换为字节数组

例如,

x = "\x01\x02\x03\x04"

我从服务器获取 x 变量,它是一个字符串,但内容是字节数组,如何将其转换为字节数组。真的坚持了下来。谢谢

标签: pythonarrayspython-3.xbytecode

解决方案


您可以encode将 string 转换为bytesobject 并将其转换为 a bytearray,或者直接将其转换为给定一些编码。

x = "\x01\x02\x03\x04"      # type: str
y = x.encode()              # type: bytes
a = bytearray(x.encode())   # type: bytearray
b = bytearray(x, 'utf-8')   # type: bytearray

请注意,bytearray(:str, ...) 指定为使用str.encode,因此后两者实际上是相同的。主要区别在于您必须明确指定编码。


推荐阅读