社会安全号码检查 - 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")
4 个回答
0
我想用正则表达式和Python3来添加一个答案。
import re
# Tests
data = [
"enter SSN (989-45-8524):",
"456748965",
"e43-45-7845",
"***-**-4598",
"4-98-4589",
"Social security Number is: [783-65-7485]",
458859635,
" Some text"
]
for ssn in data:
# Grab only digit and check length of string.
# This line is the magik
_ssn = "".join(re.findall(r"[\d]+", str(ssn)))
if len(_ssn) == 9:
print(ssn, f"{_ssn} is valid!")
2
如果不使用正则表达式,我建议一种简单的方法:
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)
注意:如果你使用的是Python 3,你需要把map转换成列表:list(map(...))
9
你可以使用re
来匹配这个模式:
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].
2
这样怎么样:
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