python - 将一串字节数组转换为字节数组
问题描述
我有一串字节数组,我想在 python 3 中将其转换为字节数组
例如,
x = "\x01\x02\x03\x04"
我从服务器获取 x 变量,它是一个字符串,但内容是字节数组,如何将其转换为字节数组。真的坚持了下来。谢谢
解决方案
您可以encode
将 string 转换为bytes
object 并将其转换为 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
,因此后两者实际上是相同的。主要区别在于您必须明确指定编码。
推荐阅读
- s4sdk - vdm Odata 版本兼容性
- python - Python - PyQt5 [PyQt5.QtWidgets 导入 QApplication 'No Module']
- python - Python:如何替换 Treeview 中的双击
- r - 从 ensembl_gene_id 获取 hgnc_symbol/gene_name
- python - 如何使用 python 提取 csv 文件的 '\r' 分隔字典
- javascript - 使用“.call”创建一个新的 JavaScript 对象而不是“new”
- java - 带有spring boot的apache cxf无法正常工作,但带有其他注释的spring boot可以正常工作?
- bash - 使用 bash 脚本对目录中的所有文件对执行程序
- python-3.x - Keras神经网络中的维度错误
- php - 从使用 file_get_contents 抓取的 HTML 表中提取数据