Python String encode Method

The encode method in Python is utilized to encode a string based on the specified encoding format. While Python strings are inherently in Unicode format, they can also be converted to different encoding standards. The process of encoding involves transforming text from one coding system to another.

Python String encode Method Syntax

It has the following syntax:

Example

encode(encoding="utf-8", errors="strict")

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.

The error parameter is assigned a default value of 'strict' and also supports several alternative values, including 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace', among others.

Return Type

It returns an encoded string.

Different Examples for Python String Encode Method

Let’s explore a few examples to gain a clearer understanding of the encode function.

Python String Encode Method Example 1

A straightforward approach to convert a Unicode string into the UTF-8 encoding format.

Example

# Python encode() function example

# Variable declaration

str = "HELLO"

encode = str.encode()

# Displaying result

print("Old value", str)

print("Encoded value", encode)

Output:

Output

Old value HELLO

Encoded value b 'HELLO'

Python String Encode Method Example 2

We are encoding a latin character

Example

� into default encoding.

# Python encode() function example

# Variable declaration

str = "H�LLO"

encode = str.encode()

# Displaying result

print("Old value", str)

print("Encoded value", encode)

Output:

Output

Old value H�LLO

Encoded value b'H\xc3\x8bLLO'

Python String Encode Method Example 3

When we attempt to encode a Latin character into ASCII, an error occurs. Refer to the example provided below.

Example

# Python encode() function example

# Variable declaration

str = "H�LLO"

encode = str.encode("ascii")

# Displaying result

print("Old value", str)

print("Encoded value", encode)

Output:

Output

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

Python String Encode Method Example 4

To disregard errors, provide 'ignore' as the second argument.

Example

# Python encode() function example

# Variable declaration

str = "H�LLO"

encode = str.encode("ascii","ignore")

# Displaying result

print("Old value", str)

print("Encoded value", encode)

Output:

Output

Old value H�LLO

Encoded value b'HLLO'

Python String Encode Method Example 5

It disregards the error and substitutes the character with a question mark.

Example

# Python encode() function example

# Variable declaration

str = "H�LLO"

encode = str.encode("ascii","replace")

# Displaying result

print("Old value", str)

print("Encoded value", encode)

Output:

Output

Old value H�LLO

Encoded value b'H?LLO'

Input Required

This code uses input(). Please provide values below: