How to Convert Bytes to String in Python ?
We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'.
This article covers different ways to convert bytes into strings in Python such as:
- Using decode() method
- Using str() function
- Using codecs.decode() method
- Using map() without using the b prefix
- Using pandas to convert bytes to strings
Let's explore them one by one:
Using .decode() method
This method is used to convert from one encoding scheme, in which the argument string is encoded to the desired encoding scheme. This works opposite to the encode.
s = b'GeeksForGeeks'
res = s.decode()
print(res, type(res))
Output
GeeksForGeeks <class 'str'>
Explanation:
- decode() converts byte sequences into human-readable strings.
- It assumes the byte object is UTF-8 encoded unless specified otherwise.
Using str() function
The str() function of Python returns the string version of the object.
s = b'GeeksForGeeks'
print(type(s))
res = str(s, 'utf-8')
print(res, type(res))
Output
<class 'bytes'> GeeksForGeeks <class 'str'>
Explanation:
- str() constructor works similarly to decode() when passed with an encoding.
- It’s a useful alternative, especially when you're not calling it on a byte object directly.
Using codecs.decode() method
The codecs module provides an alternative way to decode bytes, especially useful when dealing with different encodings.
import codecs
s = b'GeeksForGeeks'
res = codecs.decode(s)
print(res, type(res))
Output
GeeksForGeeks <class 'str'>
Using map() without using the b prefix
If you have a list of ASCII values, you can manually convert them into characters and join them into a string.
ascII = [103, 104, 105]
string = ''.join(map(chr, ascII))
print(string)
Output
ghi
Explanation:
- Each ASCII value is converted into its character using chr().
- Then characters are then joined into a complete string using .join() method.
Using pandas to convert bytes to strings
In this example, we are importing a pandas library, and we will take the input dataset and apply the decode() function.
import pandas as pd
dic = {'column' : [ b'Book', b'Pen', b'Laptop', b'CPU']}
data = pd.DataFrame(data=dic)
x = data['column'].str.decode("utf-8")
print(x)
Output
0 Book 1 Pen 2 Laptop 3 CPU Name: column, dtype: object
Explanation:
- str.decode() is applied element-wise to each entry in the column.
- Especially useful when handling data from binary files or APIs in pandas.