如何在 Python 3 中将字节转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48047079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert bytes to string in Python 3
提问by user3410960
I want to write a function that returns a string, not bytes.
the function:
我想编写一个返回字符串而不是字节的函数。
功能:
def read_image(path):
with open(path, "rb") as f:
data = f.read()
return data
image_data = read_image("/home/user/icon.jpg")
How to convert the value image_data
to type str.
If convert to string successfully, how to reconvert the string to bytes.
如何将值转换image_data
为类型 str。如果成功转换为字符串,如何将字符串重新转换为字节。
回答by MultiSkill
In order to be compatible with older code you want to return a string object the way it was back in python2 and convert a bytes object to a string object.
为了与旧代码兼容,您希望像在 python2 中一样返回字符串对象并将字节对象转换为字符串对象。
There might be an easier way, but I'm not aware of one, so I would opt to do this:
可能有一种更简单的方法,但我不知道一种方法,所以我会选择这样做:
return "".join( chr(x) for x in data)
Because iterating bytes results in integers, I'm forcibly converting them back to characters and joining the resulting array into a string.
因为迭代字节会产生整数,所以我强行将它们转换回字符并将结果数组连接到一个字符串中。
In case you need to make the code portable so that your new method still works in Python2 as well as in Python 3 (albeit might be slower):
如果您需要使代码可移植,以便您的新方法在 Python2 和 Python 3 中仍然有效(尽管可能会更慢):
return "".join( chr(x) for x in bytearray(data) )
Bytearray itterates to integers in both py2 and py3, unlike bytes.
与字节不同,Bytearray 在 py2 和 py3 中都迭代为整数。
Hope that helps.
希望有帮助。
Wrong approach:
错误的做法:
return data.decode(encoding="ascii", errors="ignore")
There might be ways to register a custom error handler, but as it is by default you are going to be missing any bytes that are outside the ascii range. Likewise using the UTF-8 encoding will mess your binary content.
可能有一些方法可以注册自定义错误处理程序,但由于默认情况下,您将丢失 ascii 范围之外的任何字节。同样,使用 UTF-8 编码会弄乱您的二进制内容。
Wrong approach 2
错误的做法2
str(b'one') == "b'one'" #for py3, but "one" for py2