Python String encode()
Python string encode() function is used to encode the string using the provided encoding. This function returns the bytes object. If we don’t provide encoding, “utf-8” encoding is used as default.
Python Bytes decode()
Python bytes decode() function is used to convert bytes to string object.
Both these functions allow us to specify the error handling scheme to use for encoding/decoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Some other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’.
Let’s look at a simple example of python string encode() decode() functions.
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 example doesn’t clearly demonstrate the use of encoding. Let’s look at another example where we will get inputs from the user and then encode it. We will have some special characters in the input string entered by the user.
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'axc3xa5bxe2x88xabcxc3xa7dxe2x88x82exc2xb4xc2xb4xc2xb4xc6x92gxc2xa91xc2xa1'
Decoded String = aåb∫cçd∂e´´´ƒg©1¡
str_original equals str_decoded = True
Reference: str.encode() API Doc, bytes.decode() API Doc