How to Decode Base64 in Python: Simple Guide
To decode base64 in Python, use the
base64.b64decode() function from the base64 module. Pass the base64 encoded string as bytes or ASCII string to this function to get the original decoded bytes.Syntax
The basic syntax to decode a base64 encoded string in Python is:
base64.b64decode(s): Decodes the base64 encoded bytes or ASCII strings.- The input
smust be bytes or ASCII string. - The output is bytes representing the original data before encoding.
python
import base64
decoded_bytes = base64.b64decode(s)Example
This example shows how to decode a base64 encoded string back to the original text.
python
import base64 # Base64 encoded string (represents 'Hello, friend!') encoded_str = 'SGVsbG8sIGZyaWVuZCE=' # Decode base64 string to bytes decoded_bytes = base64.b64decode(encoded_str) # Convert bytes to string using UTF-8 decoded_str = decoded_bytes.decode('utf-8') print(decoded_str)
Output
Hello, friend!
Common Pitfalls
Common mistakes when decoding base64 in Python include:
- Passing a Unicode string with non-ASCII characters instead of bytes or ASCII string.
- Not decoding the bytes result to a string if you want readable text.
- Ignoring padding characters
=which are required for correct decoding.
Example of wrong and right usage:
python
import base64 # Wrong: Passing a Unicode string with non-ASCII characters try: base64.b64decode('äöü') except Exception as e: print(f'Error: {e}') # Right: Pass ASCII base64 string or bytes correct = base64.b64decode('SGVsbG8=') print(correct.decode('utf-8'))
Output
Error: Non-base64 digit found
Hello
Quick Reference
Summary tips for base64 decoding in Python:
- Use
base64.b64decode()to decode base64 data. - Input must be bytes or ASCII string.
- Output is bytes; decode to string if needed.
- Handle exceptions for invalid input.
Key Takeaways
Use base64.b64decode() from the base64 module to decode base64 data.
Input must be bytes or ASCII string; output is bytes.
Decode bytes to string if you want readable text.
Watch out for invalid characters or missing padding in input.
Always handle exceptions for robust decoding.