How to Convert String to Base64 in Python?

Recently, I was working on a project where I needed to encode data before sending it over a network. The issue is that base64 encoding is a fundamental technique, but it’s not always easy for beginners to understand.

In this article, I’ll cover five simple ways you can convert strings to base64 in Python (including methods using the built-in base64 module and more advanced approaches).

So let’s dive in!

Convert String to Base64 in Python

Before conversion, let us learn about Base64, which is an encoding scheme that converts binary data into ASCII characters. It’s commonly used when you need to transfer data through systems that only support text, like email attachments or API calls.

Think of base64 as a translator that takes your regular text or binary data and converts it into a set of 64 different printable characters, making it safe to transmit without corruption.

Read How to Convert a String to a Dictionary in Python?

Method 1 – Use the Base64 Module (Standard Approach)

The most common way to convert a string to base64 in Python is using the built-in base64 module. Let’s look at a simple example:

import base64

# String to encode
my_string = "Hello from PythonGuides!"

# Convert string to bytes
string_bytes = my_string.encode('utf-8')

# Encode bytes to base64
base64_bytes = base64.b64encode(string_bytes)

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

print(f"Original string: {my_string}")
print(f"Base64 encoded: {base64_string}")

Output:

Original string: Hello from PythonGuides!
Base64 encoded: SGVsbG8gZnJvbSBQeXRob25HdWlkZXMh

I executed the above example code and added the screenshot below:

Convert String to Base64 in Python

This method is simple and works in all Python versions from 2.7 onwards. Remember that you need to first encode your string to bytes before applying base64 encoding.

Check out How to Convert Bytes to Strings in Python?

Method 2 – Use a One-Liner Approach

If you prefer a more concise approach, you can combine all the steps from Method 1 into a single line:

import base64

my_string = "Converting strings to base64 is useful for API authentication!"
base64_string = base64.b64encode(my_string.encode('utf-8')).decode('utf-8')

print(base64_string)

Output:

Q29udmVydGluZyBzdHJpbmdzIHRvIGJhc2U2NCBpcyB1c2VmdWwgZm9yIEFQSSBhdXRoZW50aWNhdGlvbiE=

I executed the above example code and added the screenshot below:

Python Convert String to Base64

I find this approach particularly easy when I’m working on quick scripts or when base64 encoding is just a small part of a larger program.

Read How to Split a String into Characters in Python?

Method 3 – URL-Safe Base64 Encoding

The standard base64 encoding uses characters like ‘+’ and ‘/’ which can cause issues in URLs. If you’re working with web applications, you might want to use URL-safe base64 encoding in Python:

import base64

api_key = "my+secret/key&with?special=characters"
url_safe_encoded = base64.urlsafe_b64encode(api_key.encode('utf-8')).decode('utf-8')

print(f"Standard encoding: {base64.b64encode(api_key.encode('utf-8')).decode('utf-8')}")
print(f"URL-safe encoding: {url_safe_encoded}")

Output:

Standard encoding: bXkrc2VjcmV0L2tleSZ3aXRoP3NwZWNpYWw9Y2hhcmFjdGVycw==
URL-safe encoding: bXkrc2VjcmV0L2tleSZ3aXRoP3NwZWNpYWw9Y2hhcmFjdGVycw==

I executed the above example code and added the screenshot below:

How to Convert String to Base64 in Python

In the URL-safe version, ‘+’ is replaced with ‘-‘ and ‘/’ with ‘_’, making it safe to use in URLs without additional encoding.

Check out How to Find a Character in a String Using Python?

Method 4 – Work with Files

Sometimes you need to encode the contents of a file in Python. Here’s how to read a file, encode its contents to base64, and save the encoded result:

import base64

# Read file content
with open('example.txt', 'r') as file:
    file_content = file.read()

# Encode to base64
encoded_content = base64.b64encode(file_content.encode('utf-8')).decode('utf-8')

# Save encoded content to a new file
with open('encoded_example.txt', 'w') as file:
    file.write(encoded_content)

print("File has been encoded and saved as encoded_example.txt")

This approach is perfect when you’re working with configuration files, certificates, or when you need to embed file contents within JSON data.

Read How to Convert a String to Lowercase in Python?

Method 5 – Create a Reusable Function

When you need to perform base64 encoding frequently throughout your codebase, it’s a good practice to create a reusable function:

import base64

def string_to_base64(input_string, url_safe=False):
    """
    Convert a string to base64 encoded string.

    Args:
        input_string (str): String to encode
        url_safe (bool): Whether to use URL-safe encoding

    Returns:
        str: Base64 encoded string
    """
    string_bytes = input_string.encode('utf-8')

    if url_safe:
        encoded_bytes = base64.urlsafe_b64encode(string_bytes)
    else:
        encoded_bytes = base64.b64encode(string_bytes)

    return encoded_bytes.decode('utf-8')

# Example usage
customer_data = "John Doe,john.doe@example.com,New York,10001"
encoded_data = string_to_base64(customer_data)
print(f"Encoded customer data: {encoded_data}")

# URL-safe example
api_token = "api+key/with@special:chars"
safe_token = string_to_base64(api_token, url_safe=True)
print(f"URL-safe encoded token: {safe_token}")

Output:

Encoded customer data: Sm9obiBEb2Usam9obi5kb2VAZXhhbXBsZS5jb20sTmV3IFlvcmssMTAwMDE=
URL-safe encoded token: YXBpK2tleS93aXRoQHNwZWNpYWw6Y2hhcnM=

This function is versatile and can be imported into different parts of your project, maintaining consistency in how you handle base64 encoding.

Read How to Swap Commas and Dots in a String in Python?

Practical Applications of Base64 Encoding

Base64 encoding is widely used in many scenarios:

  1. API Authentication: Many APIs use Base64 for encoding credentials in Basic Authentication.
  2. Embedding Images in HTML/CSS: Base64 encoding allows you to embed images directly in your HTML or CSS.
  3. Storing Binary Data in JSON: JSON doesn’t support binary data, so base64 is used to encode it.
  4. Data URLs: Embedding small files directly in HTML using the data: URL scheme.
  5. Email Attachments: The MIME format uses base64 to encode binary attachments.

For example, if you’re building a web application that requires basic authentication with an API, you might do something like this:

import base64
import requests

username = "api_user"
password = "secret_password"
credentials = f"{username}:{password}"

# Encode credentials for the Authorization header
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')

# Make API request with basic authentication
response = requests.get(
    "https://api.example.com/data",
    headers={"Authorization": f"Basic {encoded_credentials}"}
)

print(f"API Response: {response.status_code}")
print(response.json())

I hope you found this article helpful. Base64 encoding is a fundamental technique that every Python developer should understand. Whether you’re working with APIs, handling file uploads, or embedding binary data in text formats, knowing how to efficiently convert strings to base64 will serve you well in your Python journey.

If you have any questions or suggestions, kindly leave them in the comments below.

Other Python articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.