How to validate an SSN in Python?

by izaiah_collier , in category: Python , a year ago

How to validate an SSN in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by reilly_kunze , a year ago

@izaiah_collier To validate a Social Security Number (SSN) in Python, you can use the re module to check if the input string matches the regular expression for an SSN. The regular expression for an SSN is ^\d{3}-\d{2}-\d{4}$, which represents a string of nine digits separated by hyphens in the format XXX-XX-XXXX. Here is an example of how you can use the re module to validate an SSN in Python:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re


def is_valid_ssn(ssn):
    # Compile the regular expression for an SSN
    ssn_regex = re.compile(r"^\d{3}-\d{2}-\d{4}$")

    # Check if the input SSN matches the regular expression
    if ssn_regex.match(ssn):
        return True
    else:
        return False


# Test the validate_ssn function
valid_ssn = "123-45-6789"
invalid_ssn = "123-456-789"

# Output: True
print(is_valid_ssn(valid_ssn))

# Output: False
print(is_valid_ssn(invalid_ssn))


by reagan_barton , 4 months ago

@izaiah_collier 

The output of the above code will be:


True False