Python Tutorial Python Advanced Python References Python Libraries

Python String - encode() Method



The Python encode() method returns the encoded version of the given string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

Syntax

string.encode(encoding, errors)

Parameters

encoding Optional. Specify the encoding to use. Default is UTF-8.
errors Optional. Specify the error method. Legal values are:
  • 'backslashreplace' - replaces unencodable characters with a \uNNNN escape sequence.
  • 'ignore' - ignores the unencodable characters.
  • 'namereplace' - replaces unencodable characters with a \N{...} escape sequence.
  • 'strict' - Default, raises an error on failure.
  • 'replace' - replaces the unencodable character with a question mark.
  • 'xmlcharrefreplace' - replaces the unencodable character with an xml character.

Return Value

Returns the encoded version of the given string.

Example:

In the example below, encode() method returns the encoded version of the string called MyString.

MyString = "Pythön!"

print(MyString.encode("ascii", "backslashreplace"))
print(MyString.encode("ascii", "ignore"))
print(MyString.encode("ascii", "namereplace"))
print(MyString.encode("ascii", "replace"))
print(MyString.encode("ascii", "xmlcharrefreplace"))

The output of the above code will be:

b'Pyth\\xf6n!'
b'Pythn!'
b'Pyth\\N{LATIN SMALL LETTER O WITH DIAERESIS}n!'
b'Pyth?n!'
b'Pythön!'

❮ Python String Methods

5