pybase62
pybase62 is a Python module providing base62 encoding and decoding functionalities. It allows for creating short, URL-safe identifiers, as it avoids special characters like '/' or '=' found in base64. A key advantage is that the alphabetical order of the original data is preserved when encoded, meaning encoded data can be sorted without prior decoding. The current stable version is 1.0.0, released in May 2023, with development tracked on GitHub.
Warnings
- gotcha The PyPI package name is `pybase62`, but the module to import is `base62`. Importing `pybase62` will result in an `ImportError`.
- gotcha When working with byte arrays, `base62.encodebytes()` expects a `bytes` object as input, while `base62.decodebytes()` expects a `str` object (the encoded string) as input. Misunderstanding these input types can lead to `TypeError` or incorrect results.
- gotcha Multiple Python libraries exist for Base62 encoding (e.g., `pybase62`, `base62-py`, `base-62`). These implementations may use different character sets or algorithms, leading to incompatible encoded outputs. An integer encoded with one library might not be correctly decoded by another.
Install
-
pip install pybase62
Imports
- base62 module
import base62
- encode, decode, encodebytes, decodebytes
from base62 import encode, decode, encodebytes, decodebytes
Quickstart
import base62
# Encode and decode integers
original_int = 34441886726
encoded_str = base62.encode(original_int)
print(f"Encoded integer {original_int}: {encoded_str}")
decoded_int = base62.decode(encoded_str)
print(f"Decoded string '{encoded_str}': {decoded_int}")
assert original_int == decoded_int
# Encode and decode bytes
original_bytes = b'\x00\xff\xff'
encoded_bytes_str = base62.encodebytes(original_bytes)
print(f"Encoded bytes {original_bytes}: {encoded_bytes_str}")
decoded_bytes = base62.decodebytes(encoded_bytes_str)
print(f"Decoded string '{encoded_bytes_str}': {decoded_bytes}")
assert original_bytes == decoded_bytes