Python String encode() Method

You are Here:

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
encodingOptionalSpecifies the encoding to use.
Default value is 'utf-8'.
errorsOptionalSpecifies 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
NumberReturns 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"))

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Python with examples for quick and easy learning.

We are working to cover every Single Concept in Python.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author