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.

Python String encode() Method Syntax

It has the following syntax:

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.

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.

Different Examples for Python String Encode() Method 

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.

# Python encode() function example  

# Variable declaration  

str = "HELLO"  

encode = str.encode()  

# Displaying result  

print("Old value", str)  

print("Encoded value", encode)

Output:

Old value HELLO
Encoded value b 'HELLO'

Python String Encode() Method Example 2

We are encoding a latin character

� 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:

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

# Python encode() function example  

# Variable declaration  

str = "H�LLO"  

encode = str.encode("ascii")  

# Displaying result  

print("Old value", str)  

print("Encoded value", encode)

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.

# 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:

Old value H�LLO
Encoded value b'HLLO'

Python String Encode() Method Example 5

It ignores error and replace character with ? mark.

# 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:

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *