python - 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
解决方案
str
值始终是Unicode 代码点。前 256 个值是Latin-1范围,因此您可以使用该编解码器将字节直接解码为这些代码点:
out_val = in_val.decode('latin1')
但是,您想重新评估为什么要这样做。不要将二进制数据存储在字符串中,几乎总是有更好的方法来处理二进制数据。例如,如果您想以 JSON 格式存储二进制数据,那么您需要使用 Base64 或其他一些能够更好地处理边缘情况的二进制到文本编码方案,例如在解释为文本时包含转义码的二进制数据。
推荐阅读
- sql - regrouping all results in a select with a while
- python-3.x - 我想在 Tkinter 文本小部件中创建一个 png 格式的图像
- python - 问题从似乎发生变化的网站上抓取数据
- sql-server - Sql-Agent 未在 Azure 容器中的 Ubuntu SQL Server docker 容器上启动
- flutter - How do I transfer data from one function to another function in Flutter? Specifically this case
- c# - 检查二维数组c#中的某些元素是否相等
- python - Python:当 groupby 将数据框聚合到一行时,mean() 不起作用
- winapi - How to capture a maximized window accurately?
- protractor - How to compare two arrays in protractor cucumber framework
- python - 尝试使用 beautifulsoup 获取 html 内容时如何解决“不可接受”结果的错误