Python - String Method - encode() Tutorial
It will return an encoded version of the string, using the specified encoding. If no encoding is specified, UTF-8 will be used by default.
Syntax-
String.encode(encoding="encoding", errors="errors")
#encoding- (Optional) It will specify the encoding to be used.
By default, it will use UTF-8 encoding
#errors- (Optional) It is to specify the error method
some of the error methods are-
ignore - It will ignore the characters that cannot be encoded
namereplace - It will replace the character with a text explaining the character
backslashreplace - It will replace the character with a backslash that could not be encoded
strict - It will raise an error on failure
replace - It will replace the character with a question mark
xmlcharrefreplace - It will replace the character with an XML character
Example-
str1 = "Hello Pythön ß"
print(str1.encode())
print(str1.encode(encoding="UTF-8",errors="backslashreplace"))
print(str1.encode(encoding="ascii",errors="backslashreplace"))
print(str1.encode(encoding="ascii",errors="ignore"))
print(str1.encode(encoding="ascii",errors="namereplace"))
print(str1.encode(encoding="ascii",errors="replace"))
print(str1.encode(encoding="ascii",errors="xmlcharrefreplace"))
Output-
b'Hello Pyth\xc3\xb6n \xc3\x9f'
b'Hello Pyth\xc3\xb6n \xc3\x9f'
b'Hello Pyth\\xf6n \\xdf'
b'Hello Pythn '
b'Hello Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n \\N{LATIN SMALL LETTER SHARP S}'
b'Hello Pyth?n ?'
b'Hello Pythön ß'