What Is Decoder And Encoder In Python?

Asked 12 months ago
Answer 1
Viewed 202
1

Python String encode()

Python string encode() capability is utilized to encode the string utilizing the gave encoding. This capability returns the bytes object. In the event that we don't give encoding, "utf-8" encoding is utilized as default.

Python Bytes decode()

Python bytes decipher() capability is utilized to switch bytes over completely to string object. Both these capabilities permit us to indicate the mistake taking care of plan to use for encoding/deciphering blunders. The default is 'severe' implying that encoding blunders raise a UnicodeEncodeError. A few other potential qualities are 'disregard', 'supplant' and 'xmlcharrefreplace'. We should take a gander at a basic illustration of python string encode() translate() capabilities.

str_original = 'Hello'

bytes_encoded = str_original.encode(encoding='utf-8')
print(type(bytes_encoded))

str_decoded = bytes_encoded.decode()
print(type(str_decoded))

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)

Output:

<class 'bytes'>
<class 'str'>
Encoded bytes = b'Hello'
Decoded String = Hello
str_original equals str_decoded = True

Above model doesn't plainly show the utilization of encoding. We should take a gander at another model where we will get inputs from the client and afterward encode it. We will have a few exceptional characters in the info string entered by the client.

str_original = input('Please enter string data:\n')

bytes_encoded = str_original.encode()

str_decoded = bytes_encoded.decode()

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)

Output:

Please enter string data:
aåb∫cçd∂e´´´ƒg©1¡
Encoded bytes = b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1'
Decoded String = aåb∫cçd∂e´´´ƒg©1¡
str_original equals str_decoded = True

You May Also Like: What is the difference between encoder and decoder in Python?

Answered 12 months ago Wellington  ImportadoraWellington Importadora