Search code examples
pythonvalidationformat

How to make a Format Check for registration plates


def FormatCheck(choice):
    while True:
        valid = True
        userInput = input(choice).upper()
        firstPart = userInput[:2]
        secondPart = userInput[2:4]
        thirdPart = userInput[4:]
        firstBool = False
        secondBool = False
        thirdBool = False
        if firstPart.isalpha() == True:
            firstBool = True
        elif secondPart.isdigit() == True:
            secondBool = True
        elif thirdPart.isalpha() == True:
            thirdBool = True
        else:
            print ("Your registration plate is private or is incorrect")
            firstBool = False
            secondBool = False
            thirdBool = False
        if firstBool == True and secondBool == True and thirdBool == True:
            return userInput
            break


choice = FormatCheck("Please enter your registration plate")
print(choice)

Above is my very inefficient attempt at trying to display a format check on registration plates. It checks the three sections of the registration plate. THe sections being the first two characters, to make sure they were strings, then the next two characters, making sure they were integers, and the last three characters had to be strings. The code above does work, but I fee like there is an easier and shorter way of doing so, I just don't know how.

Firstly, is there a way to create some sort of boolean list, add the result of each Format Check to it, and then if any of the results are false, make the user enter the registration plate again. This would remove the need for long if statements and redundant variables.

Secondly, is there something I could do in a while loop, to check the three sections, instead of using three if statements?

Thanks in advance


Solution

  • What you are looking for is regular expressions. Python has built-in module for expressions. Here is the documentation - Regular expression operations. To use this module and regular expressions you should at first try to understand what a regular expression is.

    CODE:

    from re import compile
    
    # Pattern which must plate match to be correct.
    # It says that your input must consist of
    #    two letters -> [a-zA-Z]{2}
    #    two numbers -> [0-9]{2}
    #    three letters -> [a-zA-Z]{3}
    # Number in {} says exactly how much occurrences of symbols in
    # in [] must be in string to have positive match.  
    plate_format = compile('^[a-zA-Z]{2}[0-9]{2}[a-zA-z]{3}$')
    
    plates = ["ab12cde", "12ab34g"]
    
    for plate in plates:
        if plate_format.match(plate) is not None:
            print "Correct plate"
        else:
            print "Incorrect plate"
    

    OUTPUT:

    Correct plate
    Incorrect plate