没有编码的 Python 字符串参数

标签 python python-3.x encoding python-unicode

我正在尝试运行这段代码,它不断给出错误提示“没有编码的字符串参数”

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

有什么帮助吗?

最佳答案

您正在将一个字符串对象传递给 bytearray():

bytearray(content[current_pos:(final_pos)])

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

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

bytearray(content[current_pos:(final_pos)], 'utf8')

来自 bytearray() documentation :

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

关于没有编码的 Python 字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161243/

相关文章:

Python 用另一个字符串替换字符串(大写或小写)

python - 如何将我的 Ubuntu python3.7 升级到 python3.8 最新版本?

python-3.x - pandas multiindex - 如何在使用列时选择第二级?

python - 为什么 'thread' 模块在 Python 3.x 中重命名为 '_thread'?

php - 如何使用日文字符管理数据库中的 ID

python - 在python中将 "\x"转义字符串转换为可读字符串

python - 跳过父类(super class) __init__ 的一部分?

python - 如何为类提供类似 with-statement 的功能?

Python - 显示 json 数据

python - 无法在 python 2.7 和 django 1.9 中打开具有变音符号的文件名