The encode( ) Function is used to encode the String. By default UTF-8 is used.
x = "Héllo" y = x.encode() print("The encoded string is ",y)
In the above code, we have declared a String 'Héllo' with a special character 'é' and assigned it to a variable 'x'.
And we have used the 'encode( )' function to encode the String with UTF-8(i.e. The default).
And we get the below output.
Now, if you want to specify a custom encoding other than UTF-8. Python gives us the flexibility to do that as well in a second parameter. Also there is a third parameter that is used for errors.
A popular encoding is 'ascii'. Let us understand the below example with all the errors available.
x = "Héllo" print(x.encode(encoding="ascii",errors="backslashreplace")) print(x.encode(encoding="ascii",errors="ignore")) print(x.encode(encoding="ascii",errors="namereplace")) print(x.encode(encoding="ascii",errors="replace")) print(x.encode(encoding="ascii",errors="xmlcharrefreplace"))