Nov-11-2021, 06:35 PM
(This post was last modified: Nov-11-2021, 06:35 PM by deanhystad.)
bytes is a collection of bytes (8 bit values). str is a collection of unicode characters. encode() converts a str to bytes. decode() converts bytes to a str.
You are not using decode() correctly. data = x.decode(), not data = str(x).decode().
str(x) does not convert x from bytes to a str. it asks the class bytes to make a string representation of x, usually for the purpose of printing. bytes creates a str containing a bunch of backslashes and hex codes thinking that since it is "bytes" you want to see the hex values of the bytes.
x.decode(encoding) converts the bytes (x) to a str. This consists of grabbing one or two bytes at a time and looking up the associated unicode character. Without an "encoding" argument it assumes bytes were 8 bit ascii characters
str(x).decode() is an error str does not have a decode() method. Why would it? decode() is used to convert something else to a str. If you are already a str, you don't need to be converted to a str.
Even though you probably don't need to encode or decode in Python2 (I've never used it so I don't know for sure), I would still use encode() and decode() and bytes if such things are supported. Then the code would be mostly compatible with Python3.
You are not using decode() correctly. data = x.decode(), not data = str(x).decode().
str(x) does not convert x from bytes to a str. it asks the class bytes to make a string representation of x, usually for the purpose of printing. bytes creates a str containing a bunch of backslashes and hex codes thinking that since it is "bytes" you want to see the hex values of the bytes.
x.decode(encoding) converts the bytes (x) to a str. This consists of grabbing one or two bytes at a time and looking up the associated unicode character. Without an "encoding" argument it assumes bytes were 8 bit ascii characters
str(x).decode() is an error str does not have a decode() method. Why would it? decode() is used to convert something else to a str. If you are already a str, you don't need to be converted to a str.
Even though you probably don't need to encode or decode in Python2 (I've never used it so I don't know for sure), I would still use encode() and decode() and bytes if such things are supported. Then the code would be mostly compatible with Python3.