byte_string = b'this is a byte string'
str_decoded = byte_string.decode('utf-8') # 使用UTF-8解码
print(str_decoded) # 输出: this is a byte string
如果你只是想简单地将字节序列转换为字符串,不考虑编码,你可以使用 str() 函数:
byte_string = b'this is a byte string'
str_converted = str(byte_string, 'utf-8') # 使用UTF-8编码转换
print(str_converted) # 输出: this is a byte string
请注意,如果字节序列中包含无法解码为指定编码的字节,这将抛出 UnicodeDecodeError。如果不指定编码,Python将使用系统默认编码,这可能会导致潜在的解码错误。因此,为了避免潜在的编码问题,最好始终明确指定所需的编码格式。