如何对车牌进行格式检查

问题描述 投票:0回答:2
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)

上面是我尝试在车牌上显示格式检查的非常低效的尝试。它检查车牌的三个部分。这些部分是前两个字符,以确保它们是字符串,然后是接下来的两个字符,确保它们是整数,最后三个字符必须是字符串。上面的代码确实有效,但我觉得有一种更简单、更短的方法可以做到这一点,我只是不知道如何做。

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

其次,我可以在 while 循环中做一些事情来检查这三个部分,而不是使用三个 if 语句吗?

提前致谢

python validation format
2个回答
3
投票

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

代码:

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

0
投票

参加聚会有点晚了,但最近一直想参加

这样你就可以:

def Formateck(choice):
x = ""
for i in choice.upper():
    if i != " ":
        x = x + i
        print(i)
        print(x)
if len(x) ==7:
    return  ((not x[0:1].isdigit()) and x[0:1].isalpha()) and x[2:3].isnumeric() and x[4:].isalpha()
print(f"your string is not a valid lengh must be 7 characters {len(x)}")

打印(Formateck(“ab21 fff”)) 出现:真实

或 如果您不关心检查空间:

def Formateck(x):
return  ((not x[0:1].isdigit()) and x[0:1].isalpha()) and x[2:3].isnumeric() and x[4:].isalpha()

print(Formateck("ab21fff")) 出现:True 但不会为“ab21 fff”

© www.soinside.com 2019 - 2024. All rights reserved.