Convert bytes to string in Python using simple and effective methods to make your data human-readable. When working with files, network data, or APIs, you often receive information in byte format. While bytes are great for storage and transmission, they aren’t easy to interpret without conversion. Python provides straightforward techniques to handle this task efficiently. In this guide, we’ll walk you through why conversion is necessary and how to do it using built-in functions like decode()
. Whether you’re dealing with encoded text or raw binary data, understanding how to convert bytes to string will help you write cleaner, smarter code.
What Are Bytes in Python?
Bytes are sequences of byte (8-bit) values. They are commonly used for raw binary data such as files, network streams, or encoded strings. Byte objects look like this:
byte_data = b'Hello World'
Notice the b
prefix? That indicates the data is in byte format and not a regular string.
Why Convert Bytes to String?
Python distinguishes between bytes (raw data) and strings (human-readable text). You often need to convert bytes to strings to:
- Display readable output
- Process encoded data from files or APIs
- Log or store text-based information
Convert Bytes to String in Python Using decode()
# Convert Bytes to String in Python Using decode() data = b'Welcome to Newtum Solutions' # display input print('\nInput:') print(data) print(type(data)) # converting output = data.decode() # display output print('\nOutput:') print(output) print(type(output))
Output:
Input:
b'Welcome to Newtum Solutions'
<class 'bytes'>
Output:
Welcome to Newtum Solutions
<class 'str'>
Convert Bytes to String in Python Using str()
# Convert Bytes to String in Python Using str() data = b'Newtum Solutions' # display input print('\nInput:') print(data) print(type(data)) # converting output = str(data, 'UTF-8') # display output print('\nOutput:') print(output) print(type(output))
Output:
Input:
b'Welcome to Newtum Solutions'
<class 'bytes'>
Output:
Welcome to Newtum Solutions
<class 'str'>
Convert Bytes to String in Python Using codecs.decode()
# Convert Bytes to String in Python Using codecs.decode() # import required module import codecs data = b'Welcome to Newtum Solutions' # display input print('\nInput:') print(data) print(type(data)) # converting output = codecs.decode(data) # display output print('\nOutput:') print(output) print(type(output))
Output:
Input:
b'Welcome to Newtum Solutions'
<class 'bytes'>
Output:
Welcome to Newtum Solutions
<class 'str'>
Convert Bytes to String in Python Using map()Â
# Convert Bytes to String in Python Using map() ascII = [108, 114, 105] string = ''.join(map(chr, ascII)) print(string)
Output:
lri
Convert Bytes to String in Python Using pandas
# Convert Bytes to String in Python Using pandas import pandas as pd dic = {'column' : [ b'CD', b'DVD', b'Remote', b'Camera']} data = pd.DataFrame(data=dic) x = data['column'].str.decode("utf-8") print(x)
Output:
0 CD
1 DVD
2 Remote
3 Camera
Name: column, dtype: object
Real-Life Application: Handling Email Attachments
When working with email services or automated scripts that process emails (using libraries like imaplib
or email
), attachments and message bodies often come in bytes format—especially when encoded in MIME.
✅ Example Use Case:
You’re building a script to read incoming emails and extract the subject line and message body.
import imaplib import email mail = imaplib.IMAP4_SSL('imap.example.com') mail.login('user@example.com', 'password') mail.select('inbox') _, data = mail.search(None, 'ALL') email_ids = data[0].split() _, msg_data = mail.fetch(email_ids[-1], '(RFC822)') raw_email = msg_data[0][1] msg = email.message_from_bytes(raw_email) # Convert bytes to string for subject subject = msg['subject'] print(subject) # Already decoded by library # Convert message body bytes to string if msg.is_multipart(): for part in msg.walk(): if part.get_content_type() == 'text/plain': body_bytes = part.get_payload(decode=True) body = body_bytes.decode('utf-8') # Convert bytes to string print(body) else: body_bytes = msg.get_payload(decode=True) body = body_bytes.decode('utf-8') print(body)
🎯 Why It Matters:
Without converting from bytes to string, the email body would appear as unreadable symbols or raw binary. Decoding ensures clean, readable text for logs, user interfaces, or storage.
Interview Question
1. What is the difference between bytes and strings in Python?
Answer:
Bytes represent raw binary data and are denoted with a b''
prefix, while strings are sequences of Unicode characters. You use decode()
to convert bytes to string, and encode()
to convert a string to bytes.
2. How do you convert a byte object to a string in Python?
Answer:
Use the decode()
method with an appropriate encoding:
byte_data = b'Hello' string_data = byte_data.decode('utf-8')
This converts the byte object to a human-readable string using UTF-8 encoding.
3. What happens if you try to decode a byte object with the wrong encoding?
Answer:
Using the wrong encoding may raise a UnicodeDecodeError
. To prevent this, you can handle errors using the errors
parameter like 'ignore'
, 'replace'
, or 'backslashreplace'
.
Example:
byte_data = b'\xff' decoded = byte_data.decode('utf-8', errors='replace') # Output: �
In conclusion, converting bytes to strings in Python is essential for handling encoded data effectively. Whether you’re processing files, APIs, or network responses, understanding this conversion is crucial. Explore more Python tips and tools on Newtum’s website to enhance your coding skills and optimize your projects!