首页 > 解决方案 > Python 3 - Converting byte string to string with same content

问题描述

I am working on migrating project code from Python 2 to Python 3. One piece of code is using struct.pack which provides me value in string(Python2) and byte string(Python3) I wanted to convert byte string in python3 to normal string. Converted string should have same content to make it consistent with existing values. For e.g.

in_val = b'\0x01\0x36\0xff\0x27' # Input value
out_val = '\0x01\0x36\0xff\0x27' # Output should be this

I have one solution to convert in_val in string then explicitly remove 'b' and '\' character which will appear after its converted to string.

Is there any other solution to convert using clean way. Any help appreciated

标签: pythonpython-3.xbytepython-2.x

解决方案


str值始终是Unicode 代码点。前 256 个值是Latin-1范围,因此您可以使用该编解码器将字节直接解码为这些代码点:

out_val = in_val.decode('latin1')

但是,您想重新评估为什么要这样做。不要将二进制数据存储在字符串中,几乎总是有更好的方法来处理二进制数据。例如,如果您想以 JSON 格式存储二进制数据,那么您需要使用 Base64 或其他一些能够更好地处理边缘情况的二进制到文本编码方案,例如在解释为文本时包含转义码的二进制数据。


推荐阅读