4

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?

Community
  • 1
  • 1
Ben Blank
  • 54,908
  • 28
  • 127
  • 156

3 Answers3

8

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.

fmark
  • 57,259
  • 27
  • 100
  • 107
4

Correct. Not every store carries N or J batteries.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

To continue the analogy, that size battery may not be included in the basic package, but it's easy enough to shop on-line for plug-compatible accessories:

http://code.activestate.com/recipes/365468-number-to-string-in-arbitrary-base/

Ned Deily
  • 83,389
  • 16
  • 128
  • 151