How to Convert a Byte Array to a String in Python?

Estimated read time 2 min read

To convert a byte array to a string in Python, you can use the decode() method. Here’s an example:

# Define a byte array
byte_array = bytearray([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33])

# Convert byte array to string
string = byte_array.decode()

# Print the string
print(string)

In this example, we have a byte array byte_array containing the ASCII values of the characters ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’.

To convert the byte array to a string, we use the decode() method, which decodes the byte array using the default encoding (UTF-8) and returns a string representation.

The output will be:

Hello, world!

In this case, the byte array byte_array is converted to a string representation.

You can also specify a specific encoding to use during the decoding process by passing it as an argument to the decode() method. For example, if you have a byte array encoded in a different encoding, such as Latin-1, you can use the following code:

byte_array = bytearray([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33])
string = byte_array.decode('latin-1')

Make sure to choose the appropriate encoding based on the encoding used to generate the byte array.

If the byte array contains non-decodable or invalid byte sequences, a UnicodeDecodeError will be raised. In such cases, you may need to handle the error or specify the errors parameter to handle the decoding error.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply