编写一个程序,提示用户以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")
可以使用^{} 匹配模式:
或者
r'^\d{3}-\d{2}-\d{4}$'
使模式更易于阅读,就像@Blender提到的那样。从文档中:
这个怎么样:
如果不使用正则表达式,我建议使用一种简单的方法:
两行所有的东西一起倒塌了:
注意:如果使用Python3,则需要将映射转换为列表:
list(map(...))
相关问题 更多 >
编程相关推荐