(Last Updated On: 22/05/2023)
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