How to Convert Bytearray to String in Python
If you need to convert a Bytearray to a String in Python, then you can do the following:
This comes up when working with binary data from network sockets, file reads, or cryptographic operations where the data arrives as a bytearray and you need it as a readable string. The .decode() method (Option 2) is generally preferred since it’s more explicit about the encoding and returns a proper str type. The bytes() approach (Option 1) gives you a bytes literal, which isn’t quite the same as a string.
Option 1 – Using bytes()
b = bytearray("test", encoding="utf-8")
str1 = bytes(b)
print(str1)
Option 2 – Using bytearray.decode()
b = bytearray("test", encoding="utf-8")
str1 = b.decode()
print(str1)