【问题标题】:Python string argument without an encoding没有编码的 Python 字符串参数
【发布时间】:2015-09-18 14:32:27
【问题描述】:

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

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

有什么帮助吗?

【问题讨论】:

  • 你想得到:(ota_packet + content[current_pos:final_pos] + '\0').encode('utf-8')

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


【解决方案1】:

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

bytearray(content[current_pos:(final_pos)])

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

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

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

来自bytearray() documentation

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

  • 如果是字符串,还必须提供encoding(以及可选的errors)参数; bytearray() 然后使用str.encode() 将字符串转换为字节。

【讨论】:

    【解决方案2】:
    byteObject = b'\x18,\xa3\xf0A\x93*<bAd\x15K.A\xba'
    print(byteObject)
    print('-----------asbytearray----------')
    
    print('-------As a string------------------')
    o = base64.b64encode(bytes(str(byteObject), 'utf-8'))
    print(o.decode("utf-8"))`enter code here`
    print('--------Nonce as a string------------------')
    

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 1970-01-01
      • 2016-10-02
      • 2019-01-28
      • 2018-10-16
      • 2020-04-22
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多