The encode() method converts a string to bytes using a specified character encoding. This is essential when working with file I/O, network communication, or any context requiring byte data instead of Unicode text.
Syntax
str.encode(encoding='utf-8', errors='strict')
Parameters
Parameter
Type
Default
Description
encoding
str
'utf-8'
The encoding to use (e.g., ‘utf-8’, ‘latin-1’, ‘ascii’, ‘cp1252’)
errors
str
'strict'
How to handle encoding errors (‘strict’, ‘ignore’, ‘replace’, ‘backslashreplace’, ‘xmlcharrefreplace’)
Examples
Basic usage
text = "Hello, World!"encoded = text.encode()print(encoded)# b'Hello, World!'print(type(encoded))# <class 'bytes'>
Specifying a different encoding
text = "café"# UTF-8 (default)print(text.encode('utf-8'))# b'caf\xc3\xa9'# Latin-1 (ISO-8859-1)print(text.encode('latin-1'))# b'caf\xe9'# ASCII with replacementprint(text.encode('ascii', errors='replace'))# b'caf??'
Handling encoding errors
text = "Hello 🐍"# strict (default) - raises an exceptiontry: text.encode('ascii', errors='strict')except UnicodeEncodeError as e: print(f"strict: {e}")# ignore - skip characters that can't be encodedprint(text.encode('ascii', errors='ignore'))# b'Hello '# replace - substitute with ?print(text.encode('ascii', errors='replace'))# b'Hello ?'# backslashreplace - use \xNN notationprint(text.encode('ascii', errors='backslashreplace'))# b'Hello \\U0001f40d'# xmlcharrefreplace - use XML entity notationprint(text.encode('ascii', errors='xmlcharrefreplace'))# b'Hello 🔥'
Working with files
# Writing with specific encodingtext = "Hello, 世界!"with open("example.txt", "w", encoding="utf-8") as f: f.write(text)# Reading with specific encodingwith open("example.txt", "r", encoding="utf-8") as f: content = f.read() print(content)# Hello, 世界!