base64

Utilities

編碼與解碼

概述 base64

base64 模組是 Python 標準庫的一部分,提供將二進位資料編碼為 ASCII 文字(並將其解碼回來)的函數。 Base64 編碼在計算中隨處可見 — 在 HTML 中嵌入圖像、在電子郵件中編碼附件、在 JSON API 中傳輸二進位資料以及產生身份驗證令牌。

由於 base64 是內建的 Python 模組,因此它可以立即在PyRun中運行,無需任何導入或 micropip 下載。這是一個很好的模組,可以用來探索理解資料編碼、標記結構和二進位到文字的轉換模式。

程式碼和執行輸出

將二進位資料作為文字進行編碼、解碼和檢查。

Base64 Encoding在編輯器中執行
import base64
import json

original = "Hello from PyRun!"
encoded = base64.b64encode(original.encode()).decode()
print("Original :", original)
print("Base64   :", encoded)

decoded = base64.b64decode(encoded).decode()
print("Decoded  :", decoded)

url_safe = base64.urlsafe_b64encode(b"data for a URL: /path?q=1&v=2").decode()
print("\nURL-safe:", url_safe)

payload = {"user": "alice", "role": "admin", "exp": 9999999999}
token = base64.b64encode(json.dumps(payload).encode()).decode()
print("\nJWT-style token:", token)
print("Decoded payload:", json.loads(base64.b64decode(token)))

相關套餐

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。