11

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.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
user3410960
  • 473
  • 5
  • 8
  • 14

1 Answers1

14

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
MultiSkill
  • 406
  • 4
  • 8