Python
TypeError
Unicode
Hashing
Error Handling

How to correct TypeError Unicode-objects must be encoded before hashing?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

This error means you are passing a text string to a hashing function that expects bytes. In Python, hashing APIs such as those in hashlib operate on byte sequences, so the fix is to encode the Unicode string explicitly before hashing it.

Hash Functions Work on Bytes

A failing pattern looks like this:

python
1import hashlib
2
3text = "hello"
4hashlib.sha256(text)

The correct version encodes the string first.

python
1import hashlib
2
3text = "hello"
4digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
5print(digest)

That is the core fix.

Choose an Encoding Explicitly

utf-8 is usually the right default unless your application has a specific encoding contract.

python
value = "café"
print(hashlib.md5(value.encode("utf-8")).hexdigest())

The important thing is not just “encode somehow,” but “encode consistently.” If two systems hash the same visible text using different encodings, the resulting hashes will differ.

Keep Text and Bytes Mentally Separate

A good rule in Python is:

  • text is str
  • hash input is bytes

If you maintain that distinction clearly, errors like this become much easier to avoid. The encoding step is the bridge from human-readable text to byte representation.

Common Pitfalls

  • Passing a Python string directly to a hashing function.
  • Encoding inconsistently across different parts of the system.
  • Forgetting that non-ASCII text still needs a defined byte encoding.
  • Mixing up the digest bytes and the hexadecimal string representation.
  • Fixing the error in one place but leaving similar string-to-bytes mistakes elsewhere.

Summary

  • Hashing functions expect bytes, not Unicode strings.
  • Encode the string first, usually with UTF-8.
  • Use a consistent encoding everywhere hashes must match.
  • Keep the distinction between text and bytes clear in your code.
  • Once the input is bytes, normal hashlib usage works as expected.

Course illustration
Course illustration

All Rights Reserved.