The encode() function in python helps to convert the given string into the encoded format. If encoding not specified UTF-8 will be used as default.
string.encode(encoding='UTF-8',errors='strict') #where encodings being utf-8, ascii, etc
The encode() function takes two optional parameters. Here the argument errors can be of six types.
Parameter | Description | Required / Optional |
---|---|---|
encoding | the encoding type a string has to be encoded to | Optional |
errors | response when encoding fails | Optional |
By default function uses utf-8 encoding, in case of any failure, it raises a UnicodeDecodeError exception.
Input | Return Value |
---|---|
string | Encoded string |
# unicode string
string = 'pythön!'
# print string
print('The original string is:', string)
# default encoding to utf-8
string_utf8 = string.encode()
# print result
print('The encoded string is:', string_utf8)
Output:
The original string is: pythön! The encoded string is: b'pyth\xc3\xb6n!'
# unicode string
string = 'pythön!'
# print string
print('The original string is:', string)
# ignore error
print('The encoded string (with ignore) is:', string.encode("ascii", "ignore"))
# replace error
print('The encoded string (with replace) is:', string.encode("ascii", "replace"))
Output:
The original string is: pythön! The encoded string (with ignore) is: b'pythn!' The encoded string (with replace) is: b'pyth?n!'