Errors when using wrong encoding scheme

Example 1: Python String encode() method will raise UnicodeEncodeError if wrong encoding scheme is used

Python3




string = "¶"  # utf-8 character
 
# trying to encode using ascii scheme
print(string.encode('ascii'))


Output:

UnicodeEncodeError: 'ascii' codec can't encode character '\xb6' in position 0: ordinal not in range(128)

Example 2: Using ‘errors’ parameter to ignore errors while encoding

Python String encode() method with errors parameter set to ‘ignore’ will ignore the errors in conversion of characters into specified encoding scheme.

Python3




string = "123-¶"  # utf-8 character
 
# ignore if there are any errors
print(string.encode('ascii', errors='ignore'))


Output:

b'123-'


Python Strings encode() method

Python String encode() converts a string value into a collection of bytes, using an encoding scheme specified by the user.

Similar Reads

Python String encode() Method Syntax:

Syntax: encode(encoding, errors) Parameters:  encoding: Specifies the encoding on the basis of which encoding has to be performed.  errors: Decides how to handle the errors if they occur, e.g ‘strict’ raises Unicode error in case of exception and ‘ignore’ ignores the errors that occurred. There are six types of error response strict – default response which raises a UnicodeDecodeError exception on failure ignore – ignores the unencodable unicode from the result replace – replaces the unencodable unicode to a question mark ? xmlcharrefreplace – inserts XML character reference instead of unencodable unicode backslashreplace – inserts a \uNNNN escape sequence instead of unencodable unicode namereplace – inserts a \N{…} escape sequence instead of unencodable unicode Return:  Returns the string in the encoded form...

Python String encode() Method Example:

Python3 print("¶".encode('utf-8'))...

Errors when using wrong encoding scheme

...