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.