Python String encode() Method Tutorial

In this section, we will learn what String encode() method is and how to use it in Python.

What is String encode() Method in Python?

The Python string encode() method is used to encode a string value and return the encoded version of that string as a result.

Python String encode() Method Syntax:

string.encode(encoding, error)

String encode() Method Parameter

The method takes two arguments:

  • The first argument is a string value that specifies the encoding. This value is optional and if ignored, the default value which is UTF-8 will be used instead.
  • The second argument, which is also optional, is an error method! Basically, using this second argument, we can tell the method what to do in case of finding a character in the string that cannot be encoded properly.

Here are the values that could be used as the second argument:

backslashreplace”: this value means for those characters that cannot be encoded, a backslash should be used instead.

ignore”: using this value means ignore those characters that cannot be encoded.

namereplace”: using this value means replace those characters that cannot be encoded with a text that explains the character.

strict”: this is the default value and that means raise an error in case of a failure.

replace”: this value means, replace the character that cannot be encoded with a question mark.

xmlcharrefreplace”: this value means if there’s a character that cannot be encoded, then replace it with an XML character.

String encode() Method Return Value

The return value of this method is the encoded version of the target string value.

Example: using string encode() method in python

s1 = "My name is Ståle"

print(s1.encode(encoding="ascii",errors="backslashreplace"))

print(s1.encode(encoding="ascii",errors="ignore"))

print(s1.encode(encoding="ascii",errors="namereplace"))

print(s1.encode(encoding="ascii",errors="replace"))

print(s1.encode(encoding="ascii",errors="xmlcharrefreplace"))

Output:

b'My name is St\\xe5le'

b'My name is Stle'

b'My name is St\\N{LATIN SMALL LETTER A WITH RING ABOVE}le'

b'My name is St?le'

b'My name is Ståle'

Leave a Reply