【问题标题】:How to convert byte to string in python 3? [duplicate]如何在 python 3 中将字节转换为字符串? [复制]
【发布时间】:2019-01-25 19:31:18
【问题描述】:

我有一个变量b,其值为b'\xac\xed\x05sr\x00'。

如何将其转换为'aced05737200'?

s和r分别转换为73和72,因为它们的ascii code是73和72。

b.decode('utf-8') 给我这个错误

UnicodeDecodeError: 'utf-8' 编解码器无法在位置解码字节 0xac 0:无效的起始字节

【问题讨论】:

    标签: python python-3.x converter


    【解决方案1】:

    只需使用.hex()-方法

    >>> b = b'\xac\xed\x05sr\x00'
    >>> b.hex()
    'aced05737200'
    

    得到想要的结果,因为它不是解码或编码的问题。您的 bytestring 看起来可以生成带有十六进制数字的正确字符串对象。

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 2021-11-17
      • 2015-09-12
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 2018-08-31
      相关资源
      最近更新 更多