Reginald Reginald - 3 years ago 219
Python Question

Validate Postal Code?

I'm doing some tutorials online...and I'm stuck at an exercise:Define a function

which first checks if S represents a postal code which is valid. Note: I'm supposed to solve it with strings, lists, if statements, loops, and other basic constructs like variables and functions.

first, delete all spaces;
the remainder must be of the form
are letters (in either lower or upper case) and
are numbers.

is not a valid postal code, return the boolean
. If
is valid, return a version of the same postal code in the nice format
where each
is capital.

I've created a code for these exercise, but the grader said that is wrong, however I will post it too.

def postalValidate(S):
while " " in S:
S.remove(" ")
for i in range(1,6,2):
for j in range(0,5,2):
return True

Answer Source

This is clearly a job for regular expressions, although I don't know if you're supposed to use them in the exercise...

I'm posting this as an answer just in case you can. Otherwise, let us know...

#/usr/bin/evn python

import re
zipCode = re.compile(r"\s*(\w\d\s*){3}\s*")

if __name__ == "__main__":
    samples = [
        "           44F 4 F", #Invalid
        "  L0L0L0    ", #Valid
        "  L0  L0  L0    ", #Valid

    for sample in samples:
        if zipCode.match(sample):
            print "The string %s is a valid zipCode (nice and clean: %s)" % (sample, sample.replace(" ", "").upper())
            print "The string %s is NOT a valid zipCode" % sample


Since you can not use regular expressions, I'd recommend you change the way of thinking... Instead of checking if the characters belong to a valid postal code, I'd recommend you do the opposite: check if they DON'T belong in a valid postal code, returning False as soon as you detect a misplaced (or wrong) character:

def postalValidate(S):
    S = S.upper().replace(" ", "")
    if len(S) == 6:
        for i in range(len(S)):
            if i % 2 == 0:
                #Even index (0, 2, 4, 6...) , has to be 'letter'
                if not(S[i].isalpha()):
                    return False 
                #Odd index (1, 3, 5, 7...), must be 'number'
                if not(S[i].isdigit()):
                    return False

        #You can save some cpu ticks here... at this point, the string has to be of length 6 or you know it's not a zip
        return False
    return S

The return statement stops the execution of the current function so as soon as you realize that there's something "wrong" with the string to check, you can return False (there's no point on keeping checking once you know it's not valid, right?)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download