String method

str.encode()

Converts a string into bytes using a text encoding, UTF-8 by default, ready for files, networks or hashing.

IntermediateEvery example below runs in your browser. Change the code and press Run.

str.encode(encoding='utf-8', errors='strict')

A Python string holds characters. Computers store and send bytes. encode() translates the characters into bytes using an encoding, a set of rules for how each character becomes bytes. Almost everything today uses UTF-8, which is the default.

You need it when a tool wants bytes rather than str: hashing with hashlib, sending data over a network socket, or writing to a file opened in binary mode. bytes.decode() does the reverse.

In UTF-8 a character can take more than one byte: "é" takes 2 and "€" takes 3. So len(text) and len(text.encode()) can differ. With an encoding that cannot store a character, such as ASCII and "é", you get a UnicodeEncodeError unless you choose another errors mode.

Parameters

ParameterWhat it is
encoding
optional, default 'utf-8'
The name of the encoding: "utf-8", "ascii", "latin-1", "utf-16"…
errors
optional, default 'strict'
What to do with characters the encoding cannot store: "strict" raises an error, "replace" puts ?, "ignore" drops them, "xmlcharrefreplace" writes é-style codes.

Return value

A bytes object.

Examples

1Encode and decode

Pythoneditable
text = "café"
data = text.encode()
print(data)
print(data.decode())
Output
b'caf\xc3\xa9'
café

The b in front marks bytes. \xc3\xa9 are the two bytes UTF-8 uses for é.

2Characters vs bytes

Pythoneditable
for s in ["hello", "café", "€5"]:
    print(s, len(s), len(s.encode()))
Output
hello 5 5
café 4 5
€5 2 4

3Choose what happens to characters ASCII cannot hold

Pythoneditable
text = "café"
print(text.encode("ascii", errors="replace"))
print(text.encode("ascii", errors="ignore"))
print(text.encode("ascii", errors="xmlcharrefreplace"))
Output
b'caf?'
b'caf'
b'café'

4Hash a string with hashlib

hashlib works on bytes, so the string is encoded first.

Pythoneditable
import hashlib
digest = hashlib.sha256("hello".encode()).hexdigest()
print(digest[:16])
Output
2cf24dba5fb0a30e

Common mistakes

Encoding with an encoding that cannot hold the text

With the default errors="strict", any character the encoding cannot store raises UnicodeEncodeError. Use UTF-8, or choose an errors mode on purpose.

Pythoneditable
try:
    "Zoë".encode("ascii")
except UnicodeEncodeError:
    print("UnicodeEncodeError: ë is not ASCII")
print("Zoë".encode("utf-8"))
Output
UnicodeEncodeError: ë is not ASCII
b'Zo\xc3\xab'

Using str() to turn bytes back into text

str(data) gives the printed form "b'...'", not the text. Use decode().

Pythoneditable
data = "olá".encode()
print(str(data))
print(data.decode())
Output
b'ol\xc3\xa1'
olá

Questions people ask

What is the difference between encode() and decode()?

str.encode() turns text into bytes; bytes.decode() turns bytes back into text. Use the same encoding both ways.

Which encoding should I use?

UTF-8, unless a file or system clearly asks for something else. It can store every character.

Why do I get b'...' when I print?

You are printing bytes. Call .decode() to get the text back.

How do I open a file with a given encoding?

Pass it to open(): open("notes.txt", encoding="utf-8"). Then you read and write strings and Python encodes for you.

Spotted a mistake on this page? Tell us