Is there a good python library that can turn numbers into their respective "symbols"? [closed]
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question 开发者_如何学编程0 = 0
1 = 1
...
9 = 9
10 = a
11 = b
...
35 = z
36 = A
37 = B
...
60 = Z
61 = 10
62 = 11
...
70 = 19
71 = 1a
72 = 1b
I don't know what this is called. Base something?
All I want is a function that can convert the numbers into these, and these back to numbers.
Is there an easy function that can do this?
>>> int("a", 36)
10
>>> int("z", 36)
35
>>> int("10", 36)
36
The other direction is more complicated, but try this ActiveState recipe.
Normally base conversions make no distinction between cases. I'm not sure how to completely extend this to make that distinction, but the recipe should give you a start.
You may inherit numbers.Number:
def baseN(base,alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
class _baseN(numbers.Number):
digits=alphabet[:base]
def __init__(self,value):
if isinstance(value,int):
self.value=value
if self.value==0:
self.string='0'
else:
tmp=[abs(value)]
while tmp[0]!=0:
tmp[:1]=divmod(tmp[0],base)
tmp=[alphabet[i] for i in tmp]
tmp[0]='-' if self.value<0 else ''
self.string=''.join(tmp)
elif isinstance(value,str):
assert(value.isalnum())
self.string=str(value)
self.value=0
for d in value:
self.value=self.value*base+self.digits.index(d)
else:
self.value=0
self.string='0'
def __int__(self):
return self.value
def __str__(self):
return self.string
def __repr__(self):
return self.string
def __add__(self,another):
return self.__class__(self.value+int(another))
return None if base>len(alphabet) else _baseN
Found another bug. Change it to a factory function. Now may handle general situation.
精彩评论