如何对登记牌进行格式检查

时间:2017-11-07 16:42:06

标签: python validation format

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)

以上是我试图在登记牌上显示格式检查的非常低效的尝试。它检查登记牌的三个部分。这两个部分是前两个字符,为了确保它们是字符串,接下来的两个字符,确保它们是整数,最后三个字符必须是字符串。上面的代码确实有效,但我觉得有一种更容易和更短的方式,我只是不知道如何。

首先,有没有办法创建某种布尔列表,将每个格式检查的结果添加到其中,然后如果任何结果为假,则让用户再次进入注册板。这将消除对long if语句和冗余变量的需要。

其次,在while循环中我可以做些什么,检查三个部分,而不是使用三个if语句?

提前致谢

1 个答案:

答案 0 :(得分:2)

您正在寻找的是正则表达式。 Python有表达式的内置模块。这是文档 - Regular expression operations。要使用此模块和正则表达式,您首先应该尝试理解正则表达式是什么。

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

<强>输出

Correct plate
Incorrect plate