Skip to content

Instantly share code, notes, and snippets.

@jwz-ecust
Created March 22, 2017 01:17
Show Gist options
  • Save jwz-ecust/1c2e1a74d9a5d0778e1fb18203ad7430 to your computer and use it in GitHub Desktop.
Save jwz-ecust/1c2e1a74d9a5d0778e1fb18203ad7430 to your computer and use it in GitHub Desktop.
身份证验证
# -*- coding:utf-8 -*-
import re
IDCARD_REGEX = '[1-9][0-9]{14}([0-9]{2}[0-9X])?'
# 新身份证18位, 最后一位可能是X; 老身份证15位
def is_valid_idcard(idcard):
"""Validate id card is valid."""
if isinstance(idcard, int):
idcard = str(idcard)
if not re.match(IDCARD_REGEX, idcard):
return False
factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
items = [int(item) for item in idcard[:-1]]
copulas = sum([a * b for a, b in zip(factors, items)])
ckcodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
return ckcodes[copulas % 11].upper == idcard[-1].upper
print is_valid_idcard("320611199110123712")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment