Python String encode() Method

Last Updated:

Python String encode()

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

Default encoding is 'utf-8'.

Example

Python Compiler
txt = "Learn pythön!" x = txt.encode() print(x)

Syntax

txt.encode(encoding, errors)

Parameter Values

ValueTypeExplanation
encoding Optional Specifies the encoding to use.
Default value is 'utf-8'.
errors Optional Specifies the error method. Possible values are:
backslashreplace
Uses a backslash instead of the character that could not be encoded
ignore
Ignores the characters that cannot be encoded
namereplace
Replaces the character with a text explaining the character.
strict
Default response which raises a UnicodeDecodeError exception on failure.
replace
Replaces the character with a questionmark.
xmlcharrefreplace
Replaces the character with an xml character.

Return Value

ValueExplanation
Number Returns an encoded version of the string.

More Example

In the following example, we use "ascii" as an encoding value and all types of errors as an error method.

Example

Python Compiler
txt = "Learn pythön!" print(txt.encode("ascii", "backslashreplace")) print(txt.encode("ascii", "ignore")) print(txt.encode("ascii", "namereplace")) print(txt.encode("ascii", "replace")) print(txt.encode("ascii", "xmlcharrefreplace")) print(txt.encode("ascii", "strict"))

Share this Page

Meet the Author