写作提示用户的格式输入社会安全号码的节目ddd-dd-dddd,其中d是一个数字.程序显示"Valid SSN"正确的社会安全号码或"Invalid SSN"不正确.我几乎拥有它,只有一个问题.
我不知道如何检查它是否是正确的格式.我可以输入例如:
99-999-9999
Run Code Online (Sandbox Code Playgroud)
它会说这是有效的.我如何解决这个问题,这样我才能得到"Valid SSN"它的格式ddd-dd-dddd?
这是我的代码:
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")
Run Code Online (Sandbox Code Playgroud)
您可以使用re以匹配模式:
In [112]: import re
In [113]: ptn=re.compile(r'^\d\d\d-\d\d-\d\d\d\d$')
Run Code Online (Sandbox Code Playgroud)
或者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
Run Code Online (Sandbox Code Playgroud)
来自文档:
'^'
(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].
Run Code Online (Sandbox Code Playgroud)