Hashing and encoding in Python

Python keeps text in a str and raw data in a bytes, and most encoding work is about crossing between the two. This set covers why the character count and the byte count can differ, why a hash needs bytes rather than text, how hex writes each byte as two characters, and when to reach for the URL-safe base64 alphabet. The task runs the whole sequence once and asks you to read what it printed.

4 questions 1 task Read the lesson

Questions

Each one is marked as you go, and the explanation arrives straight after, which is the part worth reading.

4 questions, marked as you go.

1 Why does len("café") print 4 while len("café".encode()) prints 5?
2 Why does hashlib.sha256("hello") raise a TypeError?
3 Why does base64.urlsafe_b64encode exist?
4 Why is a value such as a hash written as hex, so the bytes of Hi become 4869?

Tasks

These need your own device. Run the command in Termux, then paste what it printed. The marking looks at what the output means, so spacing, version numbers and ordering do not matter. If you have not installed anything yet, the lesson covers the setup.

Encode, hash and base64 in one run

This counts the characters and the bytes in an accented word, shows two bytes as hex, hashes a message with SHA-256, and moves the same message through base64 and its URL-safe variant. Paste all five lines.

Run this in Termux On your own device. Nothing on this page executes it. The command runs in your terminal, and this box only reads what you paste back.

python3 -c "import hashlib, base64; t = 'café'; print(len(t), len(t.encode())); print('Hi'.encode().hex()); print(hashlib.sha256(b'hello termux').hexdigest()); print(base64.b64encode(b'hello termux')); print(base64.urlsafe_b64encode(bytes([255, 255, 255])))"
Marking your own work Both halves of this are checked in your browser, with no server involved, so nothing stops you from pasting output you did not run. The tasks are written so that the easiest way to pass one is to actually do it and read the result, which is the whole intention.

All sets Read the lesson