Open In App

How to Convert Bytes to String in Python ?

In this article, we are going to cover various methods that can convert bytes to strings using Python. 

Convert bytes to a string

Different ways to convert Bytes to string in Python:



Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (objects) of these classes.

Method 1: 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.






# Program for converting bytes
# to string using decode()
 
data = b'GeeksForGeeks'
 
# 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'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 2: Using str() function

The str() function of Python returns the string version of the object.




# Program for converting bytes to string using decode()
data = b'GeeksForGeeks'
 
# 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'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3: Using codecs.decode() method

This method is used to decode the binary string into normal form.




# Program for converting bytes to string using decode()
 
# import required module
import codecs
 
data = b'GeeksForGeeks'
 
# 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'GeeksForGeeks'
<class 'bytes'>

Output:
GeeksForGeeks
<class 'str'>

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 4: Using map() without using the b prefix

In this example, we will use a map() function to convert a byte to a string without using the prefix b




ascII = [103, 104, 105]
 
string = ''.join(map(chr, ascII))
print(string)

Output:

ghi

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 5: 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

Article Tags :