Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uneven base-36 support in Python?

Tags:

python

base36

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?

like image 600
Ben Blank Avatar asked Dec 12 '22 18:12

Ben Blank


2 Answers

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.

like image 67
fmark Avatar answered Dec 31 '22 00:12

fmark


Correct. Not every store carries N or J batteries.

like image 39
Ignacio Vazquez-Abrams Avatar answered Dec 31 '22 01:12

Ignacio Vazquez-Abrams