Python String encode() Method (2024)

❮ String Methods

Definition and Usage

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)

Parameter Values

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 questionmark
'xmlcharrefreplace' - replaces the character with an xml character

More Examples

Example

These examples uses ascii encoding, and a character that cannot be encoded, showing the result with different errors:

txt = "My name is Ståle"

print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))

Run example »

❮ String Methods

W3schools Pathfinder

Track your progress - it's free!

Python String encode() Method (2024)
Top Articles
Latest Posts
Article information

Author: Dr. Pierre Goyette

Last Updated:

Views: 6280

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Dr. Pierre Goyette

Birthday: 1998-01-29

Address: Apt. 611 3357 Yong Plain, West Audra, IL 70053

Phone: +5819954278378

Job: Construction Director

Hobby: Embroidery, Creative writing, Shopping, Driving, Stand-up comedy, Coffee roasting, Scrapbooking

Introduction: My name is Dr. Pierre Goyette, I am a enchanting, powerful, jolly, rich, graceful, colorful, zany person who loves writing and wants to share my knowledge and understanding with you.