codescracker
python

Python Convert bytearray to String



« Python Tutorial Python Examples »

This article is created to cover a program in Python that converts bytearray object to a string object. The program is created in similar was as done in bytes to string.

The question is, write a Python program to convert bytearray to string. The program given below is its answer:

data = b'Python Programming'
print("bytearray =", data)
data = data.decode()
print("string =", data)

The snapshot given below shows the sample output of above Python program, demonstrating the bytearray to string:

python program bytearray to string

bytearray to String in Python

This program allows user to enter the string. The string gets converted into bytearray with utf-8 encoding, then the bytearray gets converted back to the string using the decode() method, with utf-8 decoding.

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

print("\nThe string:")
print(x)

x = bytearray(x, "utf-8")
print("\nThe bytearray:")
print(x)

x = x.decode()
print("\nAgain the String:")
print(x)

Here is its sample run with user input codescracker dot com

python convert bytearray to string

If the bytearray object's data is encoded using other encoding like utf-16, then we need to use the same decoding while converting the bytearray object to string object using the decode() method.

Python Online Test


« Python Tutorial Python Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker