Python

Convert bytes to String in Python : Step By Step Implementation

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.

 

Python bytes to String Conversion ( decoding) –

Step 1:

Let’s take an example of a byte object and convert it into a string.

var_byte= b"This is demo byte"

Step 2 :

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.

 

The optional parameter in bytes to String Conversion-

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")
bytes to string error handling

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.

String to bytes Conversion ( encoding) –

1.encode() function-

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))

2. Using bytes() function-

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'))
python string to bytes using bytes()

Conclusion-

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