python符号在数字后面,是否有一个好的python库可以将数字转换为各自的“符号”?...

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?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值