Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




encode( ) FUNCTION


encode( ) Function


The encode( ) Function is used to encode the String. By default UTF-8 is used.


Example :


x = "Héllo"
y = x.encode()
print("The encoded string is ",y)


Output :



  The encoded string is  b'H\xc3\xa9llo'

In the above code, we have declared a String 'Héllo' with a special character 'é' and assigned it to a variable 'x'.


x = "Héllo"

java_Collections

And we have used the 'encode( )' function to encode the String with UTF-8(i.e. The default).


y = x.encode( )

And we get the below output.


The encoded string is  b'H\xc3\xa9llo'

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.


Example :


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"))


Output :



  b'H\\xe9llo'
  b'Hllo'
  b'H\\N{LATIN SMALL LETTER E WITH ACUTE}llo'
  b'H?llo'
  'Héllo'