Python String | encode method
Start your free 7-days trial now!
Python's str.encode(~)
method encodes the string with the specified encoding. The default is to encode using UTF-8
.
Parameters
1. encoding
| encoding type
| optional
The type of encoding to use. Default is UTF-8
.
2. errors
link | error method
| optional
Specifies how to handle errors. Default is strict
.
Type | Description |
---|---|
| Raise |
| Ignore the malformed data and continue without further notice. |
| Replace with a suitable replacement marker; for encoding this is |
| Replace with the appropriate XML character reference. |
| Replace with backslashed escape sequences. |
| Replace with |
Return value
Encoded version of the string as a bytes object.
Examples
Encoding parameter
To encode 'marché'
using UTF-8
:
x = 'marché'x.encode()
b'march\xc3\xa9'
The UTF-8 encoding for é
is represented as \xc3\xa9
where \x
indicates hexadecimal representation.
Errors parameter
To encode 'marché'
using ascii
encoding and 'replace'
error method:
y = 'marché'y.encode('ascii','replace')
b'march?'
It is not possible to represent é
in ASCII hence '?'
replacement marker is used instead of raising an error.
To encode 'marché'
using ascii
encoding and 'strict'
error method (default):
z = 'marché'z.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 5
A UnicodeEncodeError
is raised as it is not possible to represent é
in ASCII.