Python String Encode() Method

Python encode() method encodes the string according to the provided encoding standard. By default Python strings are in unicode form but can be encoded to other standards also.

Encoding is a process of converting text from one standard code to another.

Signature

Parameters

  • encoding : encoding standard, default is UTF-8
  • >
  • errors : errors mode to ignore or replace the error messages.

Both are optional. Default encoding is UTF-8.

Error parameter has a default value strict and allows other possible values 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' etc too.

Return Type

It returns an encoded string.

Let's see some examples to understand the encode() method.

Python String Encode() Method Example 1

A simple method which encode unicode string to utf-8 encoding standard.

Output:

Old value HELLO
Encoded value b 'HELLO'

Python String Encode() Method Example 2

We are encoding a latin character

Output:

Old value H�LLO
Encoded value b'H\xc3\x8bLLO'

Python String Encode() Method Example 3

We are encoding latin character into ascii, it throws an error. See the example below

Output:

UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128)

Python String Encode() Method Example 4

If we want to ignore errors, pass ignore as the second parameter.

Output:

Old value H�LLO
Encoded value b'HLLO'

Python String Encode() Method Example 5

It ignores error and replace character with ? mark.

Output:

Old value H�LLO
Encoded value b'H?LLO'

Next TopicPython Strings




Latest Courses