We can convert python bytes to string with decode() function. There are so many decoding formats like “utf-8”, “ascii” and “latin-1″ etc. In this article, we will see the bytes to string Conversion and string to byte conversion via encode and bytes() with implementation.
Let’s take an example of a byte object and convert it into a string.
var_byte= b"This is demo byte"
Now we will convert this byte object into str type.
var_str=var_byte.decode("utf-8")
Let’s run the complete code together and check out the output.
There may be errors while decoding byte object to str object. There so many ways to handle these errors.
1. strict- It will raise the error immediately if any invalid character in the object.
2. replace – It will replace the invalid character with a default set.
3. backslashreplace – while decoding the byte to the string, It will replace the error with a backslash.
4. ignore – It will simply ignore the error.
Let’s take an example.
b'\x80sample'.decode("utf-8", errors="ignore")
We can change the error parameter value from the given option. Like we have used error=”ignore”. It can be any out of the above mentioned.
It’s a reverse process to decoding. Here we convert the string to a byte object using the encode() function. Directly let’s see the conversion below.
var_byte= "This is demo byte"
print(var_byte)
var_str=var_byte.encode("utf-8")
print("The type of",var_str,"is",type(var_str))
It will work similarly to the encode() function. Let’s see the syntax for this below.
print(bytes("This is sample object in byte",'utf-8'))
Bytes to string and string to bytes is very common. We encounter this in a various tasks like sending data over rest API. I hope this article must clear concepts about this conversion. If you want to discuss more over this Bytes to string topic, Please comment below in the comment box.
Thanks
Data Science Learner Team