Content · Programming · Python

Python str.encode Method: Usage and Examples

str.encode(encoding="utf-8", errors="strict") converts Unicode text into bytes. UTF-8 can use more than one byte for a character. The original string remains text and does not become bytes. Learn with a clear example.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.encode Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.encode(encoding="utf-8", errors="strict") converts Unicode text into bytes. UTF-8 can use more than one byte for a character. The original string remains text and does not become bytes.

When You Would Use This


Prepare a greeting with accented characters for a binary file or network payload.

Step-by-Step Example


greeting_text = "Olá, Maya"
encoded_greeting = greeting_text.encode("utf-8")
print(encoded_greeting)
print(encoded_greeting.decode("utf-8"))

How the Example Works


The first output is a bytes representation, and decoding with the same encoding restores Olá, Maya. Encoding and decoding are opposite operations, not interchangeable names for formatting.

Example Output


b'Ol\xc3\xa1, Maya'
Olá, Maya

Try It Yourself


Encode a string containing € and compare the number of characters with its UTF-8 byte length.

Common Beginner Mistakes


  • Calling .encode() on bytes that are already encoded.
  • Assuming every character occupies exactly one byte.
  • Choosing errors="ignore" without realizing information may be lost.

Key Takeaways


  • str.encode(encoding="utf-8", errors="strict") converts Unicode text into bytes.
  • The first output is a bytes representation, and decoding with the same encoding restores Olá, Maya.
  • Avoid this mistake: Calling .encode() on bytes that are already encoded.
Share this resourceSend this page to someone who may find it useful.