Python Base64 Encoder & Decoder
Encode and decode Base64 for Python projects. Test your Base64 operations instantly, then copy the Python code examples for your application. All processing happens locally in your browser.
How to encode Base64 in Python
Python's base64 module handles encoding: import base64; encoded = base64.b64encode(b'Hello World').decode('utf-8'). Note that b64encode() takes bytes and returns bytes — use .decode('utf-8') to get a string. For strings: base64.b64encode('Hello World'.encode('utf-8')).decode('utf-8'). For files: with open('file.pdf', 'rb') as f: encoded = base64.b64encode(f.read()).decode('utf-8'). For URL-safe Base64 (replacing + and / with - and _): base64.urlsafe_b64encode(data).
How to decode Base64 in Python
Decode with: decoded = base64.b64decode(encoded_string). The input can be a string or bytes. For URL-safe Base64: base64.urlsafe_b64decode(encoded). Common error: binascii.Error: Invalid base64-encoded string — this means incorrect padding or invalid characters. Fix padding issues with: encoded += '=' * (4 - len(encoded) % 4). To decode Base64 image data: image_data = base64.b64decode(base64_string); with open('image.png', 'wb') as f: f.write(image_data).
Python Base64 use cases
Base64 encoding in Python is commonly used for: embedding images in HTML/CSS (data URIs), encoding email attachments (email.mime), API authentication headers (requests library: headers = {'Authorization': 'Basic ' + base64.b64encode(f'{user}:{pass}'.encode()).decode()}), storing binary data in JSON, encoding file uploads in REST APIs, and JWT token handling. The base64 module also supports Base16, Base32, and Base85 encoding variants.
Frequently Asked Questions
Why does Python Base64 require bytes, not strings?
Base64 encodes binary data. Python 3 distinguishes between str (text) and bytes (binary). You must encode strings to bytes first: 'text'.encode('utf-8'), then Base64 encode the bytes. This prevents encoding errors with Unicode characters.
How do I fix 'Incorrect padding' errors in Python Base64?
Base64 strings must be a multiple of 4 characters. Add padding: encoded += '=' * (4 - len(encoded) % 4). Or use base64.urlsafe_b64decode() which is more lenient. You can also strip whitespace first: encoded.strip().
What is the difference between b64encode and urlsafe_b64encode?
Standard b64encode uses + and / characters, which have special meaning in URLs. urlsafe_b64encode replaces them with - and _ respectively. Use urlsafe variants for data that appears in URLs, filenames, or JWT tokens.
Related Convert Tools
HTML Entity Encoder
Encode and decode HTML entities, special characters, and symbols
Image to Base64
Convert images to Base64 data URIs or decode Base64 back to images
JSON to TypeScript
Generate TypeScript interfaces and type aliases from JSON data
HTML ↔ Markdown
Convert between HTML and Markdown in either direction