Created
October 29, 2010 05:31
-
-
Save dervn/652977 to your computer and use it in GitHub Desktop.
身份证15 -> 18 转换算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding=utf-8 | |
def getNewId(oldid): | |
# 将输入的oldid参数拆分成元组 | |
a=[] | |
for i in oldid: | |
a.append(int(i)) | |
# 在第6和7位(从0开始计算)填入1和9,组成长度为17的元组 | |
a.insert(6,1) | |
a.insert(7,9) | |
# 加权因子 | |
w=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2] | |
# 校验码值 | |
md=['1','0','X','9','8','7','6','5','4','3','2'] | |
# 对前17位数字本体码加权求和,公式为:S = Sum(Ai * Wi), i = 0, ... , 16 | |
s=0 | |
for i in range(17): | |
s += a[i]*w[i] | |
# 对计算结果用11求模,得余 | |
y=divmod(s,11)[1] | |
# 取得身份证最后一位 | |
r=md[y] | |
# 组装成新身份证号 | |
newid=oldid[0:6]+"19"+oldid[6:15]+r | |
return newid | |
def chk(arg): | |
if len(arg)!=15: | |
return False | |
if not(arg.isdigit()): | |
return False | |
else: | |
return arg | |
if __name__ == '__main__': | |
id = '412827850809461' | |
if chk(id): | |
print getNewId(id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment