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.
Using the decode() method Python provides the built-in decode() method, which is used to convert bytes to a string. Let's understand the following example.
Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it.
Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.
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.
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):
return "".join( chr(x) for x in bytearray(data) )
Bytearray itterates to integers in both py2 and py3, unlike bytes.
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.
Wrong approach 2
str(b'one') == "b'one'" #for py3, but "one" for py2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With