pythonpython-3.x

What does the Python error message "a bytes-like object is required, not 'str'" mean?


I am writing some code:

image = Image.open(filename)    #opening the image
binary = bin(int(binascii.hexlify(message), 16))    #converting string into binary
binary = binary.append('1111111111111110')   #adding delimeter at the end 
binary = binary.lstrip('0b')   #removing the starting ob of binary

Because of line 2, I am getting this error:

binary = bin(int(binascii.hexlify(message), 16))

TypeError: a bytes-like object is required, not 'str'

I don’t understand this error and nothing seems to work.


Solution

  • The variable message contains a string, but it needs to be a sequence of bytes. To encode a string into bytes, you can do something like this:

    message.encode('utf-8')