python任意进制转换
python任意进制转换
import string
def module_n_converter(q, s, base=None):
"""
将自然数按照给定的字符串转换为base进制的字符串
:param q: 自然数
:param s: 字符串
:param base: int,>=2. 转换为多少进制
:return: base进制的字符串
"""
s = ''.join(sorted(set(s)))
if base is None:
base = len(s)
out = ''
dic = {i: j for i, j in zip(range(base), s)}
while q:
q, r = divmod(q, base)
out = dic[r] + out
return out
print(module_n_converter(481187, string.digits+string.ascii_lowercase)) # abab
print(int('abab', 36)) # 491187