0
0
PythonHow-ToBeginner · 3 min read

How to Encode Base64 in Python: Simple Guide with Examples

To encode data in base64 in Python, use the base64 module. Convert your data to bytes, then call base64.b64encode() to get the encoded bytes, which you can decode to a string if needed.
📐

Syntax

The basic syntax to encode data in base64 is:

  • import base64: imports the base64 module.
  • base64.b64encode(data): encodes data (bytes) to base64 bytes.
  • Convert your string to bytes before encoding using str.encode().
  • Optionally, decode the result back to a string with bytes.decode().
python
import base64

# Convert string to bytes
original_data = 'hello world'
byte_data = original_data.encode('utf-8')

# Encode bytes to base64 bytes
encoded_bytes = base64.b64encode(byte_data)

# Convert base64 bytes back to string
encoded_str = encoded_bytes.decode('utf-8')
💻

Example

This example shows how to encode a simple string to base64 and print the result.

python
import base64

text = 'Python is fun!'

# Convert string to bytes
text_bytes = text.encode('utf-8')

# Encode to base64
base64_bytes = base64.b64encode(text_bytes)

# Convert base64 bytes to string
base64_string = base64_bytes.decode('utf-8')

print(base64_string)
Output
UHl0aG9uIGlzIGZ1biE=
⚠️

Common Pitfalls

Common mistakes when encoding base64 in Python include:

  • Trying to encode a string directly without converting it to bytes first.
  • Not decoding the base64 bytes back to a string if you want to print or store it as text.
  • Confusing base64 encoding with encryption; base64 is just encoding, not secure encryption.
python
import base64

# Wrong: encoding string directly (raises TypeError)
# base64.b64encode('hello')

# Right: convert string to bytes first
encoded = base64.b64encode('hello'.encode('utf-8'))
print(encoded.decode('utf-8'))  # Output: aGVsbG8=
Output
aGVsbG8=
📊

Quick Reference

Summary tips for base64 encoding in Python:

  • Always convert strings to bytes before encoding.
  • Use base64.b64encode() to encode bytes.
  • Decode the result to string if you need readable output.
  • Base64 encoding is useful for transmitting binary data over text-based protocols.

Key Takeaways

Use the base64 module's b64encode() function to encode bytes to base64.
Always convert strings to bytes before encoding with encode('utf-8').
Decode the base64 bytes back to string with decode('utf-8') for readable output.
Base64 encoding is not encryption; it only changes data format for safe transmission.
Avoid encoding strings directly without converting to bytes to prevent errors.