Python String encode() Method
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:
|
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")
print(txt.encode(encoding="ascii",errors="strict")
Run example »