Convert bytes to a string in Python 3

17    Asked by ranjana-admin in Python , Asked on May 25, 2025

How do you convert bytes to a string in Python 3? What methods or functions are used to decode byte data into a readable text format?

Answered by kalylcie

Converting bytes to a string in Python 3 is a common task, especially when dealing with file I/O, network data, or APIs that return byte objects. So, how do you turn those raw bytes into readable text?

In Python 3, strings (type str) are Unicode by default, while bytes are sequences of raw 8-bit values. To convert bytes to a string, you need to decode them using the correct character encoding—usually UTF-8.

Here's how you can do it:

byte_data = b'Hello, world!'
string_data = byte_data.decode('utf-8')
print(string_data) # Output: Hello, world!

Key points to keep in mind:

  • Use .decode('encoding') to convert bytes to string. UTF-8 is the most common and default encoding.
  • If you're not sure what encoding to use, try 'utf-8' first.

If the bytes contain characters not compatible with the chosen encoding, Python will raise a UnicodeDecodeError. You can handle this with the errors parameter:

  byte_data.decode('utf-8', errors='ignore')

This is especially useful when reading from binary files or working with data received over a network.

Quick Tip:

  • If you're dealing with user input, APIs, or file content, always be mindful of encoding. It ensures your application behaves consistently across platforms.
  • In short, converting bytes to strings in Python 3 is as simple as using .decode(), but understanding encoding ensures you get the correct output every time.



Your Answer

Interviews

Parent Categories