社会保险号码检查-Python

2024-09-28 20:18:19 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个程序,提示用户以ddd-dd-dddd格式输入社会保险号码,其中d是一个数字。程序显示"Valid SSN"以获得正确的社会保险号码,如果不正确,则显示"Invalid SSN"。我差点就有了,只有一个问题。

我不知道如何检查它的格式是否正确。我可以输入例如:

99-999-9999

它会说它是有效的。如何解决这个问题,使我只得到格式为ddd-dd-dddd"Valid SSN"

这是我的代码:

def checkSSN():
ssn = ""
while not ssn:  
    ssn = str(input("Enter a Social Security Number in the format ddd-dd-dddd: "))
    ssn = ssn.replace("-", "") 
    if len(ssn) != 9: # checks the number of digits
        print("Invalid SSN")
    else:
        print("Valid SSN")

Tags: the用户程序格式数字dd号码ssn
3条回答

可以使用^{}匹配模式:

In [112]: import re

In [113]: ptn=re.compile(r'^\d\d\d-\d\d-\d\d\d\d$')

或者r'^\d{3}-\d{2}-\d{4}$'使模式更易于阅读,就像@Blender提到的那样。

In [114]: bool(re.match(ptn, '999-99-1234'))
Out[114]: True

In [115]: bool(re.match(ptn, '99-999-1234'))
Out[115]: False

从文档中:

'^'
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
'$'
Matches the end of the string or just before the newline at the end of the string

\d
When the UNICODE flag is not specified, matches any decimal digit; this is equivalent to the set [0-9].

这个怎么样:

SSN = raw_input("enter SSN (ddd-dd-dddd):")
chunks = SSN.split('-')
valid=False
if len(chunks) ==3: 
   if len(chunks[0])==3 and len(chunks[1])==2 and len(chunks[2])==4:
       valid=True
print valid

如果不使用正则表达式,我建议使用一种简单的方法:

def checkSSN(ssn):
    ssn = ssn.split("-")
    if map(len, ssn) != [3,2,4]:
        return False
    elif any(not x.isdigit() for x in ssn):
        return False
    return True

两行所有的东西一起倒塌了:

def checkSSN(ssn):
    ssn = ssn.split("-")
    return map(len,ssn) == [3,2,4] and all(x.isdigit() for x in ssn)

注意:如果使用Python3,则需要将映射转换为列表:list(map(...))

相关问题 更多 >