all Python 3Strings (str)function
str.encode
encodings
Encode the string to bytes using the given codec (UTF-8 by default).
Syntax
s.encode(encoding='utf-8', errors='strict')
encode() hands back bytes, a different type: it won't concatenate with str, and its len counts bytes rather than characters ('café' is five bytes in UTF-8). Anything outside the chosen codec raises UnicodeEncodeError under errors='strict'; 'ignore' and 'replace' silence it by throwing characters away for good. Going back needs bytes.decode() with the very same codec — the codec cannot be inferred from the data.
Examples
print('abc'.encode()) # → b'abc'
print('café'.encode('utf-8')) # → b'caf\xc3\xa9'
print('hi'.encode('ascii')) # → b'hi'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy