没有编码的 Python 字符串参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31161243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:34:39  来源:igfitidea点击:

Python string argument without an encoding

pythonpython-3.xencodingpython-unicode

提问by lonely

Am trying to a run this piece of code, and it keeps giving an error saying "String argument without an encoding"

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

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

Any help?

有什么帮助吗?

采纳答案by Martijn Pieters

You are passing in a string object to a bytearray():

您正在将字符串对象传递给 a bytearray()

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

You'll need to supply an encoding argument (second argument) so that it can be encoded to bytes.

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

For example, you could encode it to UTF-8:

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

##代码##

From the bytearray()documentation:

bytearray()文档

The optional sourceparameter 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().

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

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