Tutorial Study Image

Python encode()

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
 

encode() Parameters:

The encode() function takes two optional parameters. Here the argument errors can be of six types.

  • strict - default response on failure.
  • ignore - ignores the unencodable unicode
  • replace - replaces the unencodable unicode to a question mark(?)
  • xmlcharrefreplace - Instead of unencodable unicode it inserts XML character reference
  • backslashreplace - Instead of unencodable unicode it insert \uNNNN escape sequence
  • namereplace - Instead of unencodable unicode it inserts a \N{...} escape sequence
Parameter Description Required / Optional
encoding the encoding type a string has to be encoded to Optional
errors response when encoding fails Optional

encode() Return Value

By default function uses utf-8 encoding, in case of any failure, it raises a UnicodeDecodeError exception.

Input Return Value
string Encoded string

Examples of encode() method in Python

Example 1: How to encode string to default Utf-8 encoding?


# 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!'

Example 2: How encoding work with error parameter?


# 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!'