python - 社会安全号码检查 - Python

标签 python while-loop

编写一个程序,提示用户以 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/

相关文章:

python - 在客户端计算机上安装和使用 python

python - 如何使用 pyspark 将时间戳转换为 unix 格式

python - 使用 rpy2 从 python 调用 R 库 "randomForest"

sql - 使用 WHILE LOOP 在 SQL Server 2008 中迭代 SELECT 语句

java - 移动随机矩阵8*8

python 字符列表附加+

python - Elasticsearch - 同义词分析器似乎对分析不起作用

java - 在 while 循环之内或之外同步 ArrayList?

Javascript 图像加载功能挂起我的浏览器

php - 为 while 循环结果创建一个变量