I've been working with base-36 recently and have never been satisfied with the usual answer to converting ints into base-36 strings. It looks a little imbalanced…
def to_base36(value):
if not isinstance(value, int):
raise TypeError("expected int, got %s: %r" % (value.__class__.__name__, value))
if value == 0:
return "0"
if value < 0:
sign = "-"
value = -value
else:
sign = ""
result = []
while value:
value, mod = divmod(value, 36)
result.append("0123456789abcdefghijklmnopqrstuvwxyz"[mod])
return sign + "".join(reversed(result))
…when compared to converting back…
def from_base36(value):
return int(value, 36)
Does Python really not include this particular battery?
Have you tried the basin package?
>>> import basin
>>> basin.encode("0123456789abcdefghijklmnopqrstuvwxyz", 100)
'2s'
It's not batteries included, but the pypi
repository is like a convenience store for picking up batteries with the minimum of fuss.
Correct. Not every store carries N or J batteries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With