Python program to validate postal address format

Postal address validation is important for ensuring data integrity in applications. A valid postal code must meet specific criteria including proper length, numeric format, and digit pattern restrictions.

Validation Criteria

A valid postal code must satisfy the following conditions ?

  • It must be exactly 6 digits long

  • It must be a number in the range from 100000 to 999999 (cannot start with 0)

  • It must not contain more than one alternating repetitive digit pair (digits at positions i and i+2 should not be the same more than once)

Example

Let's implement a function to validate postal codes ?

def solve(s):
    n = len(s)
    nb = 0
    ok = True
    
    # Check if all characters are digits
    for i in range(n):
        ok = ok and s[i].isdigit()
    
    # Count alternating repetitive digit pairs
    for i in range(n-2):
        nb += s[i] == s[i+2]
    
    # Return True if all conditions are met
    return ok and n == 6 and s[0] != '0' and nb < 2

# Test with valid postal code
postal_code = "700035"
result = solve(postal_code)
print(f"Postal code '{postal_code}' is valid: {result}")
Postal code '700035' is valid: True

Testing Different Cases

Let's test the function with various postal codes to understand the validation better ?

def solve(s):
    n = len(s)
    nb = 0
    ok = True
    
    # Check if all characters are digits
    for i in range(n):
        ok = ok and s[i].isdigit()
    
    # Count alternating repetitive digit pairs
    for i in range(n-2):
        nb += s[i] == s[i+2]
    
    return ok and n == 6 and s[0] != '0' and nb < 2

# Test cases
test_cases = ["700035", "012345", "70A035", "7000350", "707070", "123123"]

for code in test_cases:
    result = solve(code)
    print(f"'{code}' -> {result}")
'700035' -> True
'012345' -> False
'70A035' -> False
'7000350' -> False
'707070' -> False
'123123' -> False

How It Works

The validation algorithm works in the following steps ?

  • Length Check: Ensures the postal code has exactly 6 characters

  • Digit Check: Verifies all characters are numeric digits

  • Range Check: Confirms the first digit is not '0' (ensuring range 100000-999999)

  • Pattern Check: Counts alternating repetitive pairs and ensures less than 2 occurrences

Conclusion

This postal code validation ensures proper format, length, and pattern constraints. The function effectively identifies valid 6-digit postal codes while preventing common formatting errors and suspicious digit patterns.

Updated on: 2026-03-26T15:47:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements