Home:ALL Converter>Social Security Number Check - Python

Social Security Number Check - Python

Ask Time:2014-03-06T12:54:23         Author:user3105664

Json Formatter

Writing a program that prompts the user to enter a social security number in the format ddd-dd-dddd where d is a digit. The program displays "Valid SSN" for a correct Social Security number or "Invalid SSN" if it's not correct. I nearly have it, just have one issue.

I'm not sure how to check if it's in the right format. I can enter for instance:

99-999-9999

and it'll say that it's valid. How do I work around this so that I only get "Valid SSN" if it's in the format ddd-dd-dddd?

Here's my code:

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")

Author:user3105664,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/22215314/social-security-number-check-python
zhangxaochen :

You can use re to match the pattern:\n\nIn [112]: import re\n\nIn [113]: ptn=re.compile(r'^\\d\\d\\d-\\d\\d-\\d\\d\\d\\d$')\n\n\nOr r'^\\d{3}-\\d{2}-\\d{4}$' to make the pattern much readable as @Blender mentioned.\n\nIn [114]: bool(re.match(ptn, '999-99-1234'))\nOut[114]: True\n\nIn [115]: bool(re.match(ptn, '99-999-1234'))\nOut[115]: False\n\n\nFrom the docs:\n\n'^'\n(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.\n'$'\nMatches the end of the string or just before the newline at the end of the string\n\n\\d\nWhen the UNICODE flag is not specified, matches any decimal digit; this is equivalent to the set [0-9].\n",
2014-03-06T05:00:02
David Marx :

How about this:\n\nSSN = raw_input(\"enter SSN (ddd-dd-dddd):\")\nchunks = SSN.split('-')\nvalid=False\nif len(chunks) ==3: \n if len(chunks[0])==3 and len(chunks[1])==2 and len(chunks[2])==4:\n valid=True\nprint valid\n",
2014-03-06T05:02:09
sashkello :

Without using regular expressions I'd suggest a straightforward way:\n\ndef checkSSN(ssn):\n ssn = ssn.split(\"-\")\n if map(len, ssn) != [3,2,4]:\n return False\n elif any(not x.isdigit() for x in ssn):\n return False\n return True\n\n\nTwo-liner with all things collapsed together:\n\ndef checkSSN(ssn):\n ssn = ssn.split(\"-\")\n return map(len,ssn) == [3,2,4] and all(x.isdigit() for x in ssn)\n\n\nNote: if you are using Python 3, you'll need to convert map to list: list(map(...))",
2014-03-06T05:02:00
yy