In this source code example, we show you how to perform Base64 encoding a String in Python.
Python’s Base64 module provides functions to encode binary data to Base64 encoded format and decode such encodings back to binary data.It implements Base64 encoding and decoding as specified in RFC 3548.
Python Base64 Encoding Example
import base64
data = "abc123!?$*&()'-=@~"
# Standard Base64 Encoding
encodedBytes = base64.b64encode(data.encode("utf-8"))
encodedStr = str(encodedBytes, "utf-8")
print(encodedStr)
# URL and Filename Safe Base64 Encoding
urlSafeEncodedBytes = base64.urlsafe_b64encode(data.encode("utf-8"))
urlSafeEncodedStr = str(urlSafeEncodedBytes, "utf-8")
print(urlSafeEncodedStr)
Output:
YWJjMTIzIT8kKiYoKSctPUB+
YWJjMTIzIT8kKiYoKSctPUB-
Let's understand the above source code step by step.
Standard Base64 Encoding:
data = "abc123!?$*&()'-=@~"
# Standard Base64 Encoding
encodedBytes = base64.b64encode(data.encode("utf-8"))
encodedStr = str(encodedBytes, "utf-8")
print(encodedStr)
URL and Filename Safe Base64 Encoding:
# URL and Filename Safe Base64 Encoding
urlSafeEncodedBytes = base64.urlsafe_b64encode(data.encode("utf-8"))
urlSafeEncodedStr = str(urlSafeEncodedBytes, "utf-8")
print(urlSafeEncodedStr)
Comments
Post a Comment