base64.
How It Works
base64.b64encode(binary_data) converts bytes into ASCII-compatible Base64 bytes for transport through text-oriented channels. It expands the representation and provides no secrecy or integrity protection.
Step-by-Step Example
import base64
message_bytes = 'café'.encode('utf-8')
encoded_bytes = base64.b64encode(message_bytes)
print(encoded_bytes.decode('ascii'))
print(base64.b64decode(encoded_bytes) == message_bytes)
Understanding the Example
- The expression "'café'.encode('utf-8')" supplies the value stored as 'message_bytes'. This value is then used or checked by the later statements.
- The expression 'base64.b64encode(message_bytes)' supplies the value stored as 'encoded_bytes'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
Y2Fmw6k=
True
Where This Fits in a Real Program
This transformation changes how bytes are represented for transport. It does not hide the original information or prove authenticity, so avoid using it as a substitute for encryption or a digital signature. When handling text, encode the characters to bytes first and decode restored bytes using the matching character encoding.
Practice: Try It Yourself
Encode a small UTF-8 string, then decode and check that the original bytes return.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Encoding a password with Base64 and assuming it is encrypted or protected against inspection.
- Do not mistake successful decoding or parsing for trust in the contents.
Key Takeaways
- base64.
- base64.b64encode(binary_data) converts bytes into ASCII-compatible Base64 bytes for transport through text-oriented channels.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.