首页 > 解决方案 > 将代码转换为 python 3,其中 str 和 bytes 不能再连接

问题描述

我正在尝试将此代码转换为在 Python 3 中使用,但无法弄清楚如何使其与 int 和 byte 对象之间不再存在的 concat 一起工作。编辑:这可行,但会导致一个新错误,它是完整文件的链接:https ://github.com/ndye/tiboyce/blob/master/conv_skin.py

现在主要的错误是在数据全部在内存中并等待写入之后它给了我这个错误

Traceback (most recent call last):
  File "conv_skin2.py", line 42, in <module>
    to_append = ',' * comma + '$%02X' % ord(byte)
TypeError: ord() expected string of length 1, but int found
def compress(data):
    return chr(len(data) % 256) + chr(len(data) / 256) \
        + lzf.compress(data)

标签: python

解决方案


您只需在连接之前将字符串转换为字节:

def compress(data):
    return (chr(len(data) % 256) + chr(len(data) / 256)).encode('latin1') \
        + lzf.compress(data)

请参阅如何在不编码的情况下将字符串转换为字节


推荐阅读