Python String encode() Method

Example

Encode a string in UTF-8:

txt = "My name is Ståle"
x = txt.encode()
print(x)

Run Instance

Definition and Usage

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

Syntax

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

Parameter Value

Parameter Description
encoding Optional. String. Specifies the encoding to use. The default is UTF-8.
errors

Optional. String. Specifies the error handling method. Valid values are:

  • 'backslashreplace' - Use backslashes to replace characters that cannot be encoded
  • 'ignore' - Ignore characters that cannot be encoded
  • 'namereplace' - Replace characters with text that explains the character
  • 'strict' - Default value, raises an error on failure
  • 'replace' - Replace characters with question marks
  • 'xmlcharrefreplace' - Replace characters with XML character references

More Examples

Example

These examples use ascii encoding and unencodable characters to demonstrate the results 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"))
print(txt.encode(encoding="ascii",errors="strict"))

Run Instance