Python Convert bytes to a String

This article is created to cover a program in Python that converts bytes to a string. The question is, write a Python program to convert bytes to string. Answer to this question, is the program given below.

The program given below defines a bytes object named x and then prints the value and its type. Then uses the decode() method to convert the bytes object to a string object and then prints the value and the type again of the same variable:

x = b'codescracker'

x = x.decode()

The snapshot given below shows the sample output produced by above Python program:

python convert bytes to string

But the problem is, when the bytes does not contains UTF-8 encoded data, then you need to specify the same decoding method, that was used to encode the data. For example, in the following program, the variable x contains the bytes object encoded with UTF-16, therefore while decoding into string, we need to use the same UTF-16 decoding:

x = b'\xff\xfec\x00o\x00d\x00e\x00s\x00c\x00r\x00a\x00c\x00k\x00e\x00r\x00'

x = x.decode("UTF-16")

Here is its sample output:

python program bytes to string

bytes to String in Python

Here is the last program of this article, created to allow user to enter the string. The string gets converted to bytes with utf-8 encoding, and then bytes gets converted to string again. Same thing done using utf-16 encoding and decoding:

print("Enter the String: ", end="")
x = input()

print("\nOriginal String:", x)
x = bytes(x, "utf-8")
print("bytes (with utf-8):", x)
x = x.decode("utf-8")
print("Back to the Original String:", x)
x = bytes(x, "utf-16")
print("bytes (with utf-16):", x)
x = x.decode("utf-16")
print("Again Back to the Original String:", x)

The sample run of above program with user input Python is shown in the snapshot given below:

python program convert bytes to string

Python Online Test

« Previous Program Next Program »

Follow/Like Us on Facebook

Subscribe Us on YouTube