What is the String encode() method in Python?

Introduction

Security is crucial in a variety of applications. As a result, secure password storage in the database is required, and encoded copies of strings must be saved. Python’s language contains a method called encode() that encodes strings.

The encode() method encodes strings using the provided encoding scheme. The language specifies the number of encoding techniques.

UTF-8 will be used if no encoding is given.

The encode() method in Python returns a string that has been encoded.

Syntax

string.encode(encoding=encoding, errors=errors)

Parameter

  • encoding: Optional. It is a string specifying the encoding to use. The default is UTF-8.

  • errors: Optional. This is a string specifying the error method, meaning, how to handle errors if they occur. There are six types of error messages:

    1. strict: This is the default response, which throws a UnicodeDecodeError exception if the decoding fails.
    2. replace: This substitutes the unencodable Unicode with a question mark.
    3. ignore: This ignores the unencodable Unicode from the result.
    4. xmlcharrefreplace: This replaces unencodable Unicode with an XML character reference.
    5. backslashreplace: Instead of unencodable Unicode, insert a \uNNNN escape sequence.
    6. namereplace: This replaces unencodable Unicode with an \N{…} escape sequence.

Return type

The encode() method returns the encoded version of the string.

Code

The following code shows how to use the encode() method in Python:

Example 1

We make a program to list all the encoding available in Python.

# print all encodings available
from encodings.aliases import aliases
# Printing list available
print("The available encodings are : ")
print(aliases.keys())

The code above displays all the available encoding schemes in Python.

Example 2

We use the base64 encoding scheme to encode the string and strict, which throws a UnicodeDecodeError exception if the decoding fails.

str = "This is a shot on String encode() method in python";
print "Encoded String: " + str.encode('base64','strict')

Free Resources