2017-11-07 2 views
0
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 루프에서 3 개의 if 문 대신 3 개의 섹션을 검사 할 수있는 방법이 있습니까?

미리 감사드립니다.

+0

는, 재 (정규 표현식) 모듈입니다. 표준 Python 설명서를 참조하십시오. –

+1

'isalpha()'와'isdigit()'를 직접 변수에 추가 할 수 있습니다. 그런 식으로 그들은'True' 또는'False'를 저장합니다. 그런 다음 if if firstPart 및 secondPart와 thirdPart :'if '문을 가질 수 있습니다. – kstullich

답변

1

당신이 찾고있는 것은 정규 표현식입니다. 파이썬에는 표현을위한 모듈이 내장되어 있습니다. 다음은 설명서입니다 - 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" 

OUTPUT :

당신은 아마 부분적으로 찾는거야
Correct plate 
Incorrect plate