Python String encode()

Python String encode() method returns a new string which is created from the given string, encoded using specified encoding standard.

In this tutorial, we will learn the syntax and examples for encode() method of String class.

Syntax

The syntax of String encode() method in Python is

</>
Copy
str.encode(encoding='utf-8', errors='strict')

where

ParameterRequired/
Optional
Description
encodingOptionalA string object. It specified the encoding standard to use.
errorsOptionalA string object. Specifies the action to take when an error occurs while encoding.
Following are the possible values for errors parameter, along with what they do.
1. 'backslashreplace' – uses a backslash instead of the character that could not be encoded.
2. 'ignore' – ignores the characters that cannot be encoded.
3. 'namereplace' – replaces the character with a text explaining the character.
4. 'strict' – Default, raises an error on failure.
5. 'replace' – replaces the character with a question mark.
6. 'xmlcharrefreplace' – replaces the character with an xml character.

Example

In this example, we will take a string, and encode it using ‘utf-16’.

Python Program

</>
Copy
x = 'abc'
result = x.encode(encoding='utf-16')
print(result)

Output

b'\xff\xfea\x00b\x00c\x00'

Conclusion

In this Python Tutorial, we learned how to encode a string with specific encoding using String method – encode().