本文實例講述了python3實現短網址和數字相互轉換的方法。分享給大家供大家參考。具體實現方法如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import math import decimal def convert_to_code(num): """ 將數字轉換為代碼 """ def get_num(num, out=''): num = decimal.Decimal(num) codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ" if num > 53: key = num % 54 num = math.floor(num / 54) - 1 return get_num(num, codes[int(key)] + out) else: return codes[int(num)] + out return get_num(num) def convert_to_num(code): """ 將代碼轉為數字 """ import math codes = "abcdefghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ" num = 0 num = decimal.Decimal(num) i = len(code) for char in code: i -= 1 pos = codes.find(char) num += (54 ** i) * (pos + 1) num -= 1 # 任意數的 0 次方等於1,所以需要減去 return int(num)希望本文所述對大家的Python程序設計有所幫助。