Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert bytes to string in Python 3 [duplicate]

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.

like image 417
user3410960 Avatar asked Jan 01 '18 04:01

user3410960


People also ask

Which method is used to convert raw byte data to a string a ToString () b convert () C encode () D decode ()?

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.

Which method is used to convert raw byte data to a string in Python?

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.

Can you convert byte into string?

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.


1 Answers

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
like image 115
MultiSkill Avatar answered Oct 28 '22 07:10

MultiSkill