20
loading...
This website collects cookies to deliver better user experience
decode()
methodstr()
methodcodecs.decode()
methoddecode()
method. It takes the byte object and converts it to string. It uses the UTF-8 encoding by default if you don’t specify anything. The decode()
method is nothing but the opposite of the encode.# Python converting bytes to string using decode()
data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))
# coversion happens from bytes to string
output = data.decode()
print(output)
print("Coverted type is ", type(output))
Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is <class 'str'>
str()
method. You need to pass the correct encoding to this method else it will lead to incorrect conversion.# Python converting bytes to string using str()
data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))
# coversion happens from bytes to string
output = str(data,'UTF-8')
print(output)
print("Coverted type is ", type(output))
Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is <class 'str'>
codecs
module comes as a standard built-in module in Python, and it has a decode()
method which takes the input bytes and returns the string as output data.# Python converting bytes to string using decode()
import codecs
data = b'ItsMyCode \xf0\x9f\x8d\x95!'
print(data)
print("Before conversion type is", type(data))
# coversion happens from bytes to string
output = codecs.decode(data)
print(output)
print("Coverted type is ", type(output))
Before conversion type is <class 'bytes'>
ItsMyCode 🍕!
Coverted type is <class 'str'>