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)
上面是我尝试在车牌上显示格式检查的非常低效的尝试。它检查车牌的三个部分。这些部分是前两个字符,以确保它们是字符串,然后是接下来的两个字符,确保它们是整数,最后三个字符必须是字符串。上面的代码确实有效,但我觉得有一种更简单、更短的方法可以做到这一点,我只是不知道如何做。
首先,有没有办法创建某种 bool 列表,将每个格式检查的结果添加到其中,然后如果任何结果为假,则让用户再次输入车牌。这将消除对长 if 语句和冗余变量的需要。
其次,我可以在 while 循环中做一些事情来检查这三个部分,而不是使用三个 if 语句吗?
提前致谢
最佳答案
您正在寻找的是正则表达式。 Python 有内置的表达式模块。这是文档 - Regular expression operations 。要使用此模块和正则表达式,您应该首先尝试了解正则表达式是什么。
代码:
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
关于python - 如何对车牌进行格式检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163143/