Python String encode() Method
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:
|
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"))