没有编码的Python字符串参数

lon*_*ely 40 python encoding python-3.x python-unicode

我试图运行这段代码,并不断给出错误说"没有编码的字符串参数"

ota_packet = ota_packet.encode('utf-8') + bytearray(content[current_pos:(final_pos)]) + '\0'.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

有帮助吗?

Mar*_*ers 63

您将字符串对象传递给bytearray():

bytearray(content[current_pos:(final_pos)])
Run Code Online (Sandbox Code Playgroud)

您需要提供编码参数(第二个参数),以便可以将其编码为字节.

例如,您可以将其编码为UTF-8:

bytearray(content[current_pos:(final_pos)], 'utf8')
Run Code Online (Sandbox Code Playgroud)

bytearray()文档:

可选的source参数可用于以几种不同的方式初始化数组:

  • 如果它是一个字符串,您还必须提供编码(和可选的,错误)参数; bytearray()然后使用将字符串转换为字节str.encode().