编写一个程序,提示用户以 ddd-dd-dddd
格式输入社会安全号码,其中 d
是一个数字。如果社会安全号码正确,该程序会显示 “有效 SSN”
,如果不正确,则会显示 “无效 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")
最佳答案
您可以使用 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].
关于python - 社会安全号码检查 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22215314/