Python

Python Menu

Python

Python String encode() - Definition, Syntax, Parameters, Examples

Definition

The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

Syntax

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

Parameters

Parameter Description
encoding Optional. A String specifying the encoding to use. Default is UTF-8
errors Optional. A String specifying the error method. Legal 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, raises an error on failure
"replace" - replaces the character with a question mark
"xmlcharrefreplace" - replaces the character with a xml character

Examples:

myStr = "Hello Ståle!" result = myStr.encode() print(result) # using ASCII encoding print(myStr.encode(encoding="ascii",errors="backslashreplace")) print(myStr.encode(encoding="ascii",errors="ignore")) print(myStr.encode(encoding="ascii",errors="namereplace")) print(myStr.encode(encoding="ascii",errors="replace")) print(myStr.encode(encoding="ascii",errors="xmlcharrefreplace"))

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods