October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Convert a String to Base64 in Python

Use UTF-8 to turn a Python string into bytes, Base64-encode those bytes, then decode the result as ASCII when you need a string.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encode the string as bytes, pass those bytes to Python’s Base64 encoder, and decode the result as ASCII if you need a normal Python string:

import base64

text = "Hello, world!"
encoded = base64.b64encode(text.encode("utf-8")).decode("ascii")
print(encoded)  # SGVsbG8sIHdvcmxkIQ==

Why does Base64 need bytes?

Base64 represents byte data using a limited set of ASCII characters; it does not directly encode Python text. A Python str is Unicode text, so first serialize it into bytes with a text encoding. Python’s base64.b64encode() accepts bytes-like data and returns encoded bytes. The final .decode("ascii") converts those Base64 bytes into a Python string. See the Python 3.14.8 Base64 documentation and codec documentation.

How to decode Base64 back into text

Reverse the operations: decode the Base64 representation to bytes, then decode those bytes with the same text encoding used to encode the original string.

decoded_text = base64.b64decode(encoded).decode("utf-8")
print(decoded_text)  # Hello, world!

This round trip works when the Base64 value represents bytes originally produced from the text using UTF-8. If the data came from another system, use the text encoding that system used.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which text encoding should you use?

Use the encoding expected by the receiving system. UTF-8 is a practical default for general Unicode text; Python’s codec documentation describes encoding strings to bytes and decoding bytes back to strings. If an API or file format specifies a different encoding, use that consistently on both sides.

Do not use str(some_bytes) to turn encoded bytes into text. Without an encoding argument, str() produces a representation such as "b'Zoot!'", rather than decoding the byte contents. Python documents this behavior in its built-in types documentation.

When should you use URL-safe Base64?

Use the URL-safe variant when the receiving system expects Base64 in a URL or filesystem name:

encoded_url = base64.urlsafe_b64encode(text.encode("utf-8")).decode("ascii")
decoded_bytes = base64.urlsafe_b64decode(encoded_url)
decoded_text = decoded_bytes.decode("utf-8")

URL-safe Base64 replaces + with - and / with _. It may still include = padding. Follow the receiving system’s requirements before removing padding, and use urlsafe_b64decode() for the corresponding decode operation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to handle malformed or untrusted Base64

By default, base64.b64decode() uses validate=False: characters outside the Base64 alphabet are discarded before padding is checked. Set validate=True if unexpected characters should cause an error instead:

decoded_bytes = base64.b64decode(encoded_input, validate=True)

Strict validation raises binascii.Error for non-alphabet characters; incorrect padding can also raise binascii.Error. Choose permissive or strict behavior according to the input format you accept.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Base64 is not encryption

Base64 is an encoding for representing bytes as text, not a method of protecting data. Anyone who obtains a Base64 value can decode it, so do not use Base64 alone to keep confidential information secret.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.